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,300
pragma_directive.py
NioTheFirst_ScType/slither/core/declarations/pragma_directive.py
from typing import List, TYPE_CHECKING from slither.core.source_mapping.source_mapping import SourceMapping if TYPE_CHECKING: from slither.core.scope.scope import FileScope class Pragma(SourceMapping): def __init__(self, directive: List[str], scope: "FileScope"): super().__init__() self._directive = directive self.scope: "FileScope" = scope @property def directive(self) -> List[str]: """ list(str) """ return self._directive @property def version(self) -> str: return "".join(self.directive[1:]) @property def name(self) -> str: return self.version @property def is_solidity_version(self) -> bool: if len(self._directive) > 0: return self._directive[0].lower() == "solidity" return False @property def is_abi_encoder_v2(self) -> bool: if len(self._directive) == 2: return self._directive[0] == "experimental" and self._directive[1] == "ABIEncoderV2" return False def __str__(self): return "pragma " + "".join(self.directive)
1,126
Python
.py
33
27.121212
96
0.620499
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,301
modifier.py
NioTheFirst_ScType/slither/core/declarations/modifier.py
""" Modifier module """ from .function_contract import FunctionContract class Modifier(FunctionContract): pass
121
Python
.py
6
17.5
47
0.787611
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,302
enum_top_level.py
NioTheFirst_ScType/slither/core/declarations/enum_top_level.py
from typing import TYPE_CHECKING, List from slither.core.declarations import Enum from slither.core.declarations.top_level import TopLevel if TYPE_CHECKING: from slither.core.scope.scope import FileScope class EnumTopLevel(Enum, TopLevel): def __init__(self, name: str, canonical_name: str, values: List[str], scope: "FileScope"): super().__init__(name, canonical_name, values) self.file_scope: "FileScope" = scope
443
Python
.py
9
45.111111
94
0.746512
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,303
function_contract.py
NioTheFirst_ScType/slither/core/declarations/function_contract.py
""" Function module """ from typing import TYPE_CHECKING, List, Tuple from slither.core.children.child_contract import ChildContract from slither.core.children.child_inheritance import ChildInheritance from slither.core.declarations import Function # pylint: disable=import-outside-toplevel,too-many-instance-attributes,too-many-statements,too-many-lines if TYPE_CHECKING: from slither.core.declarations import Contract from slither.core.scope.scope import FileScope class FunctionContract(Function, ChildContract, ChildInheritance): @property def canonical_name(self) -> str: """ str: contract.func_name(type1,type2) Return the function signature without the return values """ if self._canonical_name is None: name, parameters, _ = self.signature self._canonical_name = ( ".".join([self.contract_declarer.name] + self._internal_scope + [name]) + "(" + ",".join(parameters) + ")" ) return self._canonical_name def is_declared_by(self, contract: "Contract") -> bool: """ Check if the element is declared by the contract :param contract: :return: """ return self.contract_declarer == contract @property def file_scope(self) -> "FileScope": return self.contract.file_scope # endregion ################################################################################### ################################################################################### # region Functions ################################################################################### ################################################################################### @property def functions_shadowed(self) -> List["Function"]: """ Return the list of functions shadowed Returns: list(core.Function) """ candidates = [c.functions_declared for c in self.contract.inheritance] candidates = [candidate for sublist in candidates for candidate in sublist] return [f for f in candidates if f.full_name == self.full_name] # endregion ################################################################################### ################################################################################### # region Summary information ################################################################################### ################################################################################### def get_summary( self, ) -> Tuple[str, str, str, List[str], List[str], List[str], List[str], List[str]]: """ Return the function summary Returns: (str, str, str, list(str), list(str), listr(str), list(str), list(str); contract_name, name, visibility, modifiers, vars read, vars written, internal_calls, external_calls_as_expressions """ return ( self.contract_declarer.name, self.full_name, self.visibility, [str(x) for x in self.modifiers], [str(x) for x in self.state_variables_read + self.solidity_variables_read], [str(x) for x in self.state_variables_written], [str(x) for x in self.internal_calls], [str(x) for x in self.external_calls_as_expressions], ) # endregion ################################################################################### ################################################################################### # region SlithIr and SSA ################################################################################### ################################################################################### def generate_slithir_ssa(self, all_ssa_state_variables_instances): from slither.slithir.utils.ssa import add_ssa_ir, transform_slithir_vars_to_ssa from slither.core.dominators.utils import ( compute_dominance_frontier, compute_dominators, ) compute_dominators(self.nodes) compute_dominance_frontier(self.nodes) transform_slithir_vars_to_ssa(self) if not self.contract.is_incorrectly_constructed: add_ssa_ir(self, all_ssa_state_variables_instances)
4,429
Python
.py
95
38.389474
126
0.484371
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,304
contract.py
NioTheFirst_ScType/slither/core/declarations/contract.py
"""" Contract module """ import logging from collections import defaultdict from pathlib import Path from typing import Optional, List, Dict, Callable, Tuple, TYPE_CHECKING, Union, Set from crytic_compile.platform import Type as PlatformType from slither.core.cfg.scope import Scope from slither.core.solidity_types.type import Type from slither.core.source_mapping.source_mapping import SourceMapping from slither.core.declarations.function import Function, FunctionType, FunctionLanguage from slither.detectors.my_detectors.ExtendedType import ExtendedType from slither.utils.erc import ( ERC20_signatures, ERC165_signatures, ERC223_signatures, ERC721_signatures, ERC1820_signatures, ERC777_signatures, ERC1155_signatures, ERC2612_signatures, ERC1363_signatures, ERC4524_signatures, ERC4626_signatures, ) from slither.utils.tests_pattern import is_test_contract # pylint: disable=too-many-lines,too-many-instance-attributes,import-outside-toplevel,too-many-nested-blocks if TYPE_CHECKING: from slither.utils.type_helpers import LibraryCallType, HighLevelCallType, InternalCallType from slither.core.declarations import ( Enum, Event, Modifier, EnumContract, StructureContract, FunctionContract, ) from slither.slithir.variables.variable import SlithIRVariable from slither.core.variables.variable import Variable from slither.core.variables.state_variable import StateVariable from slither.core.compilation_unit import SlitherCompilationUnit from slither.core.declarations.custom_error_contract import CustomErrorContract from slither.core.scope.scope import FileScope LOGGER = logging.getLogger("Contract") class Contract(SourceMapping): # pylint: disable=too-many-public-methods """ Contract class """ def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope"): super().__init__() self._name: Optional[str] = None self._id: Optional[int] = None self._inheritance: List["Contract"] = [] # all contract inherited, c3 linearization self._immediate_inheritance: List["Contract"] = [] # immediate inheritance self._ex = ExtendedType() self._ex.function_name = "global" # Constructors called on contract's definition # contract B is A(1) { .. self._explicit_base_constructor_calls: List["Contract"] = [] self._enums: Dict[str, "EnumContract"] = {} self._structures: Dict[str, "StructureContract"] = {} self._events: Dict[str, "Event"] = {} # map accessible variable from name -> variable # do not contain private variables inherited from contract self._variables: Dict[str, "StateVariable"] = {} self._variables_ordered: List["StateVariable"] = [] self._modifiers: Dict[str, "Modifier"] = {} self._functions: Dict[str, "FunctionContract"] = {} self._linearizedBaseContracts: List[int] = [] self._custom_errors: Dict[str, "CustomErrorContract"] = {} # The only str is "*" self._using_for: Dict[Union[str, Type], List[Type]] = {} self._using_for_complete: Dict[Union[str, Type], List[Type]] = None self._kind: Optional[str] = None self._is_interface: bool = False self._is_library: bool = False self._signatures: Optional[List[str]] = None self._signatures_declared: Optional[List[str]] = None self._is_upgradeable: Optional[bool] = None self._is_upgradeable_proxy: Optional[bool] = None self._upgradeable_version: Optional[str] = None self.is_top_level = False # heavily used, so no @property self._initial_state_variables: List["StateVariable"] = [] # ssa self._is_incorrectly_parsed: bool = False self._available_functions_as_dict: Optional[Dict[str, "Function"]] = None self._all_functions_called: Optional[List["InternalCallType"]] = None self.compilation_unit: "SlitherCompilationUnit" = compilation_unit self.file_scope: "FileScope" = scope # memoize self._state_variables_used_in_reentrant_targets: Optional[ Dict["StateVariable", Set[Union["StateVariable", "Function"]]] ] = None ################################################################################### ################################################################################### # region General's properties ################################################################################### ################################################################################### @property def name(self) -> str: """str: Name of the contract.""" assert self._name return self._name @property def extok(self): return self._ex @name.setter def name(self, name: str): self._ex.name = name self._name = name @property def id(self) -> int: """Unique id.""" assert self._id return self._id @id.setter def id(self, new_id): """Unique id.""" self._id = new_id @property def contract_kind(self) -> Optional[str]: """ contract_kind can be None if the legacy ast format is used :return: """ return self._kind @contract_kind.setter def contract_kind(self, kind): self._kind = kind @property def is_interface(self) -> bool: return self._is_interface @is_interface.setter def is_interface(self, is_interface: bool): self._is_interface = is_interface @property def is_library(self) -> bool: return self._is_library @is_library.setter def is_library(self, is_library: bool): self._is_library = is_library # endregion ################################################################################### ################################################################################### # region Structures ################################################################################### ################################################################################### @property def structures(self) -> List["StructureContract"]: """ list(Structure): List of the structures """ return list(self._structures.values()) @property def structures_inherited(self) -> List["StructureContract"]: """ list(Structure): List of the inherited structures """ return [s for s in self.structures if s.contract != self] @property def structures_declared(self) -> List["StructureContract"]: """ list(Structues): List of the structures declared within the contract (not inherited) """ return [s for s in self.structures if s.contract == self] @property def structures_as_dict(self) -> Dict[str, "StructureContract"]: return self._structures # endregion ################################################################################### ################################################################################### # region Enums ################################################################################### ################################################################################### @property def enums(self) -> List["EnumContract"]: return list(self._enums.values()) @property def enums_inherited(self) -> List["EnumContract"]: """ list(Enum): List of the inherited enums """ return [e for e in self.enums if e.contract != self] @property def enums_declared(self) -> List["EnumContract"]: """ list(Enum): List of the enums declared within the contract (not inherited) """ return [e for e in self.enums if e.contract == self] @property def enums_as_dict(self) -> Dict[str, "EnumContract"]: return self._enums # endregion ################################################################################### ################################################################################### # region Events ################################################################################### ################################################################################### @property def events(self) -> List["Event"]: """ list(Event): List of the events """ return list(self._events.values()) @property def events_inherited(self) -> List["Event"]: """ list(Event): List of the inherited events """ return [e for e in self.events if e.contract != self] @property def events_declared(self) -> List["Event"]: """ list(Event): List of the events declared within the contract (not inherited) """ return [e for e in self.events if e.contract == self] @property def events_as_dict(self) -> Dict[str, "Event"]: return self._events # endregion ################################################################################### ################################################################################### # region Using for ################################################################################### ################################################################################### @property def using_for(self) -> Dict[Union[str, Type], List[Type]]: return self._using_for @property def using_for_complete(self) -> Dict[Union[str, Type], List[Type]]: """ Dict[Union[str, Type], List[Type]]: Dict of merged local using for directive with top level directive """ def _merge_using_for(uf1, uf2): result = {**uf1, **uf2} for key, value in result.items(): if key in uf1 and key in uf2: result[key] = value + uf1[key] return result if self._using_for_complete is None: result = self.using_for top_level_using_for = self.file_scope.using_for_directives for uftl in top_level_using_for: result = _merge_using_for(result, uftl.using_for) self._using_for_complete = result return self._using_for_complete # endregion ################################################################################### ################################################################################### # region Custom Errors ################################################################################### ################################################################################### @property def custom_errors(self) -> List["CustomErrorContract"]: """ list(CustomErrorContract): List of the contract's custom errors """ return list(self._custom_errors.values()) @property def custom_errors_inherited(self) -> List["CustomErrorContract"]: """ list(CustomErrorContract): List of the inherited custom errors """ return [s for s in self.custom_errors if s.contract != self] @property def custom_errors_declared(self) -> List["CustomErrorContract"]: """ list(CustomErrorContract): List of the custom errors declared within the contract (not inherited) """ return [s for s in self.custom_errors if s.contract == self] @property def custom_errors_as_dict(self) -> Dict[str, "CustomErrorContract"]: return self._custom_errors # endregion ################################################################################### ################################################################################### # region Variables ################################################################################### ################################################################################### @property def variables(self) -> List["StateVariable"]: """ Returns all the accessible variables (do not include private variable from inherited contract) list(StateVariable): List of the state variables. Alias to self.state_variables. """ return list(self.state_variables) @property def variables_as_dict(self) -> Dict[str, "StateVariable"]: return self._variables @property def state_variables(self) -> List["StateVariable"]: """ Returns all the accessible variables (do not include private variable from inherited contract). Use state_variables_ordered for all the variables following the storage order list(StateVariable): List of the state variables. """ return list(self._variables.values()) @property def state_variables_entry_points(self) -> List["StateVariable"]: """ list(StateVariable): List of the state variables that are public. """ return [var for var in self._variables.values() if var.visibility == "public"] @property def state_variables_ordered(self) -> List["StateVariable"]: """ list(StateVariable): List of the state variables by order of declaration. """ return list(self._variables_ordered) def add_variables_ordered(self, new_vars: List["StateVariable"]): self._variables_ordered += new_vars @property def state_variables_inherited(self) -> List["StateVariable"]: """ list(StateVariable): List of the inherited state variables """ return [s for s in self.state_variables if s.contract != self] @property def state_variables_declared(self) -> List["StateVariable"]: """ list(StateVariable): List of the state variables declared within the contract (not inherited) """ return [s for s in self.state_variables if s.contract == self] @property def slithir_variables(self) -> List["SlithIRVariable"]: """ List all of the slithir variables (non SSA) """ slithir_variabless = [f.slithir_variables for f in self.functions + self.modifiers] # type: ignore slithir_variables = [item for sublist in slithir_variabless for item in sublist] return list(set(slithir_variables)) @property def state_variables_used_in_reentrant_targets( self, ) -> Dict["StateVariable", Set[Union["StateVariable", "Function"]]]: """ Returns the state variables used in reentrant targets. Heuristics: - Variable used (read/write) in entry points that are reentrant - State variables that are public """ from slither.core.variables.state_variable import StateVariable if self._state_variables_used_in_reentrant_targets is None: reentrant_functions = [f for f in self.functions_entry_points if f.is_reentrant] variables_used: Dict[ StateVariable, Set[Union[StateVariable, "Function"]] ] = defaultdict(set) for function in reentrant_functions: for ir in function.all_slithir_operations(): state_variables = [v for v in ir.used if isinstance(v, StateVariable)] for state_variable in state_variables: variables_used[state_variable].add(ir.node.function) for variable in [v for v in self.state_variables if v.visibility == "public"]: variables_used[variable].add(variable) self._state_variables_used_in_reentrant_targets = variables_used return self._state_variables_used_in_reentrant_targets # endregion ################################################################################### ################################################################################### # region Constructors ################################################################################### ################################################################################### @property def constructor(self) -> Optional["Function"]: """ Return the contract's immediate constructor. If there is no immediate constructor, returns the first constructor executed, following the c3 linearization Return None if there is no constructor. """ cst = self.constructors_declared if cst: return cst for inherited_contract in self.inheritance: cst = inherited_contract.constructors_declared if cst: return cst return None @property def constructors_declared(self) -> Optional["Function"]: return next( ( func for func in self.functions if func.is_constructor and func.contract_declarer == self ), None, ) @property def constructors(self) -> List["Function"]: """ Return the list of constructors (including inherited) """ return [func for func in self.functions if func.is_constructor] @property def explicit_base_constructor_calls(self) -> List["Function"]: """ list(Function): List of the base constructors called explicitly by this contract definition. Base constructors called by any constructor definition will not be included. Base constructors implicitly called by the contract definition (without parenthesis) will not be included. On "contract B is A(){..}" it returns the constructor of A """ return [c.constructor for c in self._explicit_base_constructor_calls if c.constructor] # endregion ################################################################################### ################################################################################### # region Functions and Modifiers ################################################################################### ################################################################################### @property def functions_signatures(self) -> List[str]: """ Return the signatures of all the public/eterxnal functions/state variables :return: list(string) the signatures of all the functions that can be called """ if self._signatures is None: sigs = [ v.full_name for v in self.state_variables if v.visibility in ["public", "external"] ] sigs += {f.full_name for f in self.functions if f.visibility in ["public", "external"]} self._signatures = list(set(sigs)) return self._signatures @property def functions_signatures_declared(self) -> List[str]: """ Return the signatures of the public/eterxnal functions/state variables that are declared by this contract :return: list(string) the signatures of all the functions that can be called and are declared by this contract """ if self._signatures_declared is None: sigs = [ v.full_name for v in self.state_variables_declared if v.visibility in ["public", "external"] ] sigs += { f.full_name for f in self.functions_declared if f.visibility in ["public", "external"] } self._signatures_declared = list(set(sigs)) return self._signatures_declared @property def functions(self) -> List["FunctionContract"]: """ list(Function): List of the functions """ return list(self._functions.values()) def available_functions_as_dict(self) -> Dict[str, "FunctionContract"]: if self._available_functions_as_dict is None: self._available_functions_as_dict = { f.full_name: f for f in self._functions.values() if not f.is_shadowed } return self._available_functions_as_dict def add_function(self, func: "FunctionContract"): self._functions[func.canonical_name] = func def set_functions(self, functions: Dict[str, "FunctionContract"]): """ Set the functions :param functions: dict full_name -> function :return: """ self._functions = functions @property def functions_inherited(self) -> List["FunctionContract"]: """ list(Function): List of the inherited functions """ return [f for f in self.functions if f.contract_declarer != self] @property def functions_declared(self) -> List["FunctionContract"]: """ list(Function): List of the functions defined within the contract (not inherited) """ return [f for f in self.functions if f.contract_declarer == self] @property def functions_entry_points(self) -> List["FunctionContract"]: """ list(Functions): List of public and external functions """ return [ f for f in self.functions if f.visibility in ["public", "external"] and not f.is_shadowed or f.is_fallback ] @property def modifiers(self) -> List["Modifier"]: """ list(Modifier): List of the modifiers """ return list(self._modifiers.values()) def available_modifiers_as_dict(self) -> Dict[str, "Modifier"]: return {m.full_name: m for m in self._modifiers.values() if not m.is_shadowed} def set_modifiers(self, modifiers: Dict[str, "Modifier"]): """ Set the modifiers :param modifiers: dict full_name -> modifier :return: """ self._modifiers = modifiers @property def modifiers_inherited(self) -> List["Modifier"]: """ list(Modifier): List of the inherited modifiers """ return [m for m in self.modifiers if m.contract_declarer != self] @property def modifiers_declared(self) -> List["Modifier"]: """ list(Modifier): List of the modifiers defined within the contract (not inherited) """ return [m for m in self.modifiers if m.contract_declarer == self] @property def functions_and_modifiers(self) -> List["Function"]: """ list(Function|Modifier): List of the functions and modifiers """ return self.functions + self.modifiers # type: ignore @property def functions_and_modifiers_inherited(self) -> List["Function"]: """ list(Function|Modifier): List of the inherited functions and modifiers """ return self.functions_inherited + self.modifiers_inherited # type: ignore @property def functions_and_modifiers_declared(self) -> List["Function"]: """ list(Function|Modifier): List of the functions and modifiers defined within the contract (not inherited) """ return self.functions_declared + self.modifiers_declared # type: ignore def available_elements_from_inheritances( self, elements: Dict[str, "Function"], getter_available: Callable[["Contract"], List["FunctionContract"]], ) -> Dict[str, "Function"]: """ :param elements: dict(canonical_name -> elements) :param getter_available: fun x :return: """ # keep track of the contracts visited # to prevent an ovveride due to multiple inheritance of the same contract # A is B, C, D is C, --> the second C was already seen inherited_elements: Dict[str, "FunctionContract"] = {} accessible_elements = {} contracts_visited = [] for father in self.inheritance_reverse: functions: Dict[str, "FunctionContract"] = { v.full_name: v for v in getter_available(father) if v.contract not in contracts_visited and v.function_language != FunctionLanguage.Yul # Yul functions are not propagated in the inheritance } contracts_visited.append(father) inherited_elements.update(functions) for element in inherited_elements.values(): accessible_elements[element.full_name] = elements[element.canonical_name] return accessible_elements # endregion ################################################################################### ################################################################################### # region Inheritance ################################################################################### ################################################################################### @property def inheritance(self) -> List["Contract"]: """ list(Contract): Inheritance list. Order: the first elem is the first father to be executed """ return list(self._inheritance) @property def immediate_inheritance(self) -> List["Contract"]: """ list(Contract): List of contracts immediately inherited from (fathers). Order: order of declaration. """ return list(self._immediate_inheritance) @property def inheritance_reverse(self) -> List["Contract"]: """ list(Contract): Inheritance list. Order: the last elem is the first father to be executed """ return list(reversed(self._inheritance)) def set_inheritance( self, inheritance: List["Contract"], immediate_inheritance: List["Contract"], called_base_constructor_contracts: List["Contract"], ): self._inheritance = inheritance self._immediate_inheritance = immediate_inheritance self._explicit_base_constructor_calls = called_base_constructor_contracts @property def derived_contracts(self) -> List["Contract"]: """ list(Contract): Return the list of contracts derived from self """ candidates = self.compilation_unit.contracts return [c for c in candidates if self in c.inheritance] # endregion ################################################################################### ################################################################################### # region Getters from/to object ################################################################################### ################################################################################### def get_functions_reading_from_variable(self, variable: "Variable") -> List["Function"]: """ Return the functions reading the variable """ return [f for f in self.functions if f.is_reading(variable)] def get_functions_writing_to_variable(self, variable: "Variable") -> List["Function"]: """ Return the functions writting the variable """ return [f for f in self.functions if f.is_writing(variable)] def get_function_from_full_name(self, full_name: str) -> Optional["Function"]: """ Return a function from a full name The full name differs from the solidity's signature are the type are conserved For example contract type are kept, structure are not unrolled, etc Args: full_name (str): signature of the function (without return statement) Returns: Function """ return next( (f for f in self.functions if f.full_name == full_name and not f.is_shadowed), None, ) def get_function_from_signature(self, function_signature: str) -> Optional["Function"]: """ Return a function from a signature Args: function_signature (str): signature of the function (without return statement) Returns: Function """ return next( ( f for f in self.functions if f.solidity_signature == function_signature and not f.is_shadowed ), None, ) def get_modifier_from_signature(self, modifier_signature: str) -> Optional["Modifier"]: """ Return a modifier from a signature :param modifier_signature: """ return next( (m for m in self.modifiers if m.full_name == modifier_signature and not m.is_shadowed), None, ) def get_function_from_canonical_name(self, canonical_name: str) -> Optional["Function"]: """ Return a function from a a canonical name (contract.signature()) Args: canonical_name (str): canonical name of the function (without return statement) Returns: Function """ return next((f for f in self.functions if f.canonical_name == canonical_name), None) def get_modifier_from_canonical_name(self, canonical_name: str) -> Optional["Modifier"]: """ Return a modifier from a canonical name (contract.signature()) Args: canonical_name (str): canonical name of the modifier Returns: Modifier """ return next((m for m in self.modifiers if m.canonical_name == canonical_name), None) def get_state_variable_from_name(self, variable_name: str) -> Optional["StateVariable"]: """ Return a state variable from a name :param variable_name: """ return next((v for v in self.state_variables if v.name == variable_name), None) def get_state_variable_from_canonical_name( self, canonical_name: str ) -> Optional["StateVariable"]: """ Return a state variable from a canonical_name Args: canonical_name (str): name of the variable Returns: StateVariable """ return next((v for v in self.state_variables if v.name == canonical_name), None) def get_structure_from_name(self, structure_name: str) -> Optional["Structure"]: """ Return a structure from a name Args: structure_name (str): name of the structure Returns: Structure """ return next((st for st in self.structures if st.name == structure_name), None) def get_structure_from_canonical_name(self, structure_name: str) -> Optional["Structure"]: """ Return a structure from a canonical name Args: structure_name (str): canonical name of the structure Returns: Structure """ return next((st for st in self.structures if st.canonical_name == structure_name), None) def get_event_from_signature(self, event_signature: str) -> Optional["Event"]: """ Return an event from a signature Args: event_signature (str): signature of the event Returns: Event """ return next((e for e in self.events if e.full_name == event_signature), None) def get_event_from_canonical_name(self, event_canonical_name: str) -> Optional["Event"]: """ Return an event from a canonical name Args: event_canonical_name (str): name of the event Returns: Event """ return next((e for e in self.events if e.canonical_name == event_canonical_name), None) def get_enum_from_name(self, enum_name: str) -> Optional["Enum"]: """ Return an enum from a name Args: enum_name (str): name of the enum Returns: Enum """ return next((e for e in self.enums if e.name == enum_name), None) def get_enum_from_canonical_name(self, enum_name) -> Optional["Enum"]: """ Return an enum from a canonical name Args: enum_name (str): canonical name of the enum Returns: Enum """ return next((e for e in self.enums if e.canonical_name == enum_name), None) def get_functions_overridden_by(self, function: "Function") -> List["Function"]: """ Return the list of functions overriden by the function Args: (core.Function) Returns: list(core.Function) """ candidatess = [c.functions_declared for c in self.inheritance] candidates = [candidate for sublist in candidatess for candidate in sublist] return [f for f in candidates if f.full_name == function.full_name] # endregion ################################################################################### ################################################################################### # region Recursive getters ################################################################################### ################################################################################### @property def all_functions_called(self) -> List["InternalCallType"]: """ list(Function): List of functions reachable from the contract Includes super, and private/internal functions not shadowed """ if self._all_functions_called is None: all_functions = [f for f in self.functions + self.modifiers if not f.is_shadowed] # type: ignore all_callss = [f.all_internal_calls() for f in all_functions] + [list(all_functions)] all_calls = [item for sublist in all_callss for item in sublist] all_calls = list(set(all_calls)) all_constructors = [c.constructor for c in self.inheritance if c.constructor] all_constructors = list(set(all_constructors)) set_all_calls = set(all_calls + list(all_constructors)) self._all_functions_called = [c for c in set_all_calls if isinstance(c, Function)] return self._all_functions_called @property def all_state_variables_written(self) -> List["StateVariable"]: """ list(StateVariable): List all of the state variables written """ all_state_variables_writtens = [ f.all_state_variables_written() for f in self.functions + self.modifiers # type: ignore ] all_state_variables_written = [ item for sublist in all_state_variables_writtens for item in sublist ] return list(set(all_state_variables_written)) @property def all_state_variables_read(self) -> List["StateVariable"]: """ list(StateVariable): List all of the state variables read """ all_state_variables_reads = [ f.all_state_variables_read() for f in self.functions + self.modifiers # type: ignore ] all_state_variables_read = [ item for sublist in all_state_variables_reads for item in sublist ] return list(set(all_state_variables_read)) @property def all_library_calls(self) -> List["LibraryCallType"]: """ list((Contract, Function): List all of the libraries func called """ all_high_level_callss = [f.all_library_calls() for f in self.functions + self.modifiers] # type: ignore all_high_level_calls = [item for sublist in all_high_level_callss for item in sublist] return list(set(all_high_level_calls)) @property def all_high_level_calls(self) -> List["HighLevelCallType"]: """ list((Contract, Function|Variable)): List all of the external high level calls """ all_high_level_callss = [f.all_high_level_calls() for f in self.functions + self.modifiers] # type: ignore all_high_level_calls = [item for sublist in all_high_level_callss for item in sublist] return list(set(all_high_level_calls)) # endregion ################################################################################### ################################################################################### # region Summary information ################################################################################### ################################################################################### def get_summary(self, include_shadowed=True) -> Tuple[str, List[str], List[str], List, List]: """Return the function summary :param include_shadowed: boolean to indicate if shadowed functions should be included (default True) Returns: (str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries) """ func_summaries = [ f.get_summary() for f in self.functions if (not f.is_shadowed or include_shadowed) ] modif_summaries = [ f.get_summary() for f in self.modifiers if (not f.is_shadowed or include_shadowed) ] return ( self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries, ) def is_signature_only(self) -> bool: """Detect if the contract has only abstract functions Returns: bool: true if the function are abstract functions """ return all((not f.is_implemented) for f in self.functions) # endregion ################################################################################### ################################################################################### # region ERC conformance ################################################################################### ################################################################################### def ercs(self) -> List[str]: """ Return the ERC implemented :return: list of string """ all_erc = [ ("ERC20", self.is_erc20), ("ERC165", self.is_erc165), ("ERC1820", self.is_erc1820), ("ERC223", self.is_erc223), ("ERC721", self.is_erc721), ("ERC777", self.is_erc777), ("ERC2612", self.is_erc2612), ("ERC1363", self.is_erc1363), ("ERC4626", self.is_erc4626), ] return [erc for erc, is_erc in all_erc if is_erc()] def is_erc20(self) -> bool: """ Check if the contract is an erc20 token Note: it does not check for correct return values :return: Returns a true if the contract is an erc20 """ full_names = self.functions_signatures return all(s in full_names for s in ERC20_signatures) def is_erc165(self) -> bool: """ Check if the contract is an erc165 token Note: it does not check for correct return values :return: Returns a true if the contract is an erc165 """ full_names = self.functions_signatures return all(s in full_names for s in ERC165_signatures) def is_erc1820(self) -> bool: """ Check if the contract is an erc1820 Note: it does not check for correct return values :return: Returns a true if the contract is an erc165 """ full_names = self.functions_signatures return all(s in full_names for s in ERC1820_signatures) def is_erc223(self) -> bool: """ Check if the contract is an erc223 token Note: it does not check for correct return values :return: Returns a true if the contract is an erc223 """ full_names = self.functions_signatures return all(s in full_names for s in ERC223_signatures) def is_erc721(self) -> bool: """ Check if the contract is an erc721 token Note: it does not check for correct return values :return: Returns a true if the contract is an erc721 """ full_names = self.functions_signatures return all(s in full_names for s in ERC721_signatures) def is_erc777(self) -> bool: """ Check if the contract is an erc777 Note: it does not check for correct return values :return: Returns a true if the contract is an erc165 """ full_names = self.functions_signatures return all(s in full_names for s in ERC777_signatures) def is_erc1155(self) -> bool: """ Check if the contract is an erc1155 Note: it does not check for correct return values :return: Returns a true if the contract is an erc1155 """ full_names = self.functions_signatures return all(s in full_names for s in ERC1155_signatures) def is_erc4626(self) -> bool: """ Check if the contract is an erc4626 Note: it does not check for correct return values :return: Returns a true if the contract is an erc4626 """ full_names = self.functions_signatures return all(s in full_names for s in ERC4626_signatures) def is_erc2612(self) -> bool: """ Check if the contract is an erc2612 Note: it does not check for correct return values :return: Returns a true if the contract is an erc2612 """ full_names = self.functions_signatures return all(s in full_names for s in ERC2612_signatures) def is_erc1363(self) -> bool: """ Check if the contract is an erc1363 Note: it does not check for correct return values :return: Returns a true if the contract is an erc1363 """ full_names = self.functions_signatures return all(s in full_names for s in ERC1363_signatures) def is_erc4524(self) -> bool: """ Check if the contract is an erc4524 Note: it does not check for correct return values :return: Returns a true if the contract is an erc4524 """ full_names = self.functions_signatures return all(s in full_names for s in ERC4524_signatures) @property def is_token(self) -> bool: """ Check if the contract follows one of the standard ERC token :return: """ return ( self.is_erc20() or self.is_erc721() or self.is_erc165() or self.is_erc223() or self.is_erc777() or self.is_erc1155() ) def is_possible_erc20(self) -> bool: """ Checks if the provided contract could be attempting to implement ERC20 standards. :return: Returns a boolean indicating if the provided contract met the token standard. """ # We do not check for all the functions, as name(), symbol(), might give too many FPs full_names = self.functions_signatures return ( "transfer(address,uint256)" in full_names or "transferFrom(address,address,uint256)" in full_names or "approve(address,uint256)" in full_names ) def is_possible_erc721(self) -> bool: """ Checks if the provided contract could be attempting to implement ERC721 standards. :return: Returns a boolean indicating if the provided contract met the token standard. """ # We do not check for all the functions, as name(), symbol(), might give too many FPs full_names = self.functions_signatures return ( "ownerOf(uint256)" in full_names or "safeTransferFrom(address,address,uint256,bytes)" in full_names or "safeTransferFrom(address,address,uint256)" in full_names or "setApprovalForAll(address,bool)" in full_names or "getApproved(uint256)" in full_names or "isApprovedForAll(address,address)" in full_names ) @property def is_possible_token(self) -> bool: """ Check if the contract is a potential token (it might not implement all the functions) :return: """ return self.is_possible_erc20() or self.is_possible_erc721() # endregion ################################################################################### ################################################################################### # region Dependencies ################################################################################### ################################################################################### def is_from_dependency(self) -> bool: return self.compilation_unit.core.crytic_compile.is_dependency( self.source_mapping.filename.absolute ) # endregion ################################################################################### ################################################################################### # region Test ################################################################################### ################################################################################### @property def is_truffle_migration(self) -> bool: """ Return true if the contract is the Migrations contract needed for Truffle :return: """ if self.compilation_unit.core.crytic_compile.platform == PlatformType.TRUFFLE: if self.name == "Migrations": paths = Path(self.source_mapping.filename.absolute).parts if len(paths) >= 2: return paths[-2] == "contracts" and paths[-1] == "migrations.sol" return False @property def is_test(self) -> bool: return is_test_contract(self) or self.is_truffle_migration # endregion ################################################################################### ################################################################################### # region Function analyses ################################################################################### ################################################################################### def update_read_write_using_ssa(self): for function in self.functions + self.modifiers: function.update_read_write_using_ssa() # endregion ################################################################################### ################################################################################### # region Upgradeability ################################################################################### ################################################################################### @property def is_upgradeable(self) -> bool: if self._is_upgradeable is None: self._is_upgradeable = False if self.is_upgradeable_proxy: return False initializable = self.file_scope.get_contract_from_name("Initializable") if initializable: if initializable in self.inheritance: self._is_upgradeable = True else: for contract in self.inheritance + [self]: # This might lead to false positive # Not sure why pylint is having a trouble here # pylint: disable=no-member lower_name = contract.name.lower() if "upgradeable" in lower_name or "upgradable" in lower_name: self._is_upgradeable = True break if "initializable" in lower_name: self._is_upgradeable = True break return self._is_upgradeable @is_upgradeable.setter def is_upgradeable(self, upgradeable: bool): self._is_upgradeable = upgradeable @property def is_upgradeable_proxy(self) -> bool: from slither.core.cfg.node import NodeType from slither.slithir.operations import LowLevelCall if self._is_upgradeable_proxy is None: self._is_upgradeable_proxy = False if "Proxy" in self.name: self._is_upgradeable_proxy = True return True for f in self.functions: if f.is_fallback: for node in f.all_nodes(): for ir in node.irs: if isinstance(ir, LowLevelCall) and ir.function_name == "delegatecall": self._is_upgradeable_proxy = True return self._is_upgradeable_proxy if node.type == NodeType.ASSEMBLY: inline_asm = node.inline_asm if inline_asm: if "delegatecall" in inline_asm: self._is_upgradeable_proxy = True return self._is_upgradeable_proxy return self._is_upgradeable_proxy @is_upgradeable_proxy.setter def is_upgradeable_proxy(self, upgradeable_proxy: bool): self._is_upgradeable_proxy = upgradeable_proxy @property def upgradeable_version(self) -> Optional[str]: return self._upgradeable_version @upgradeable_version.setter def upgradeable_version(self, version_name: str): self._upgradeable_version = version_name # endregion ################################################################################### ################################################################################### # region Internals ################################################################################### ################################################################################### @property def is_incorrectly_constructed(self) -> bool: """ Return true if there was an internal Slither's issue when analyzing the contract :return: """ return self._is_incorrectly_parsed @is_incorrectly_constructed.setter def is_incorrectly_constructed(self, incorrect: bool): self._is_incorrectly_parsed = incorrect def add_constructor_variables(self): from slither.core.declarations.function_contract import FunctionContract if self.state_variables: for (idx, variable_candidate) in enumerate(self.state_variables): if variable_candidate.expression and not variable_candidate.is_constant: constructor_variable = FunctionContract(self.compilation_unit) constructor_variable.set_function_type(FunctionType.CONSTRUCTOR_VARIABLES) constructor_variable.set_contract(self) constructor_variable.set_contract_declarer(self) constructor_variable.set_visibility("internal") # For now, source mapping of the constructor variable is the whole contract # Could be improved with a targeted source mapping constructor_variable.set_offset(self.source_mapping, self.compilation_unit) self._functions[constructor_variable.canonical_name] = constructor_variable prev_node = self._create_node( constructor_variable, 0, variable_candidate, constructor_variable ) variable_candidate.node_initialization = prev_node counter = 1 for v in self.state_variables[idx + 1 :]: if v.expression and not v.is_constant: next_node = self._create_node( constructor_variable, counter, v, prev_node.scope ) v.node_initialization = next_node prev_node.add_son(next_node) next_node.add_father(prev_node) prev_node = next_node counter += 1 break for (idx, variable_candidate) in enumerate(self.state_variables): if variable_candidate.expression and variable_candidate.is_constant: constructor_variable = FunctionContract(self.compilation_unit) constructor_variable.set_function_type( FunctionType.CONSTRUCTOR_CONSTANT_VARIABLES ) constructor_variable.set_contract(self) constructor_variable.set_contract_declarer(self) constructor_variable.set_visibility("internal") # For now, source mapping of the constructor variable is the whole contract # Could be improved with a targeted source mapping constructor_variable.set_offset(self.source_mapping, self.compilation_unit) self._functions[constructor_variable.canonical_name] = constructor_variable prev_node = self._create_node( constructor_variable, 0, variable_candidate, constructor_variable ) variable_candidate.node_initialization = prev_node counter = 1 for v in self.state_variables[idx + 1 :]: if v.expression and v.is_constant: next_node = self._create_node( constructor_variable, counter, v, prev_node.scope ) v.node_initialization = next_node prev_node.add_son(next_node) next_node.add_father(prev_node) prev_node = next_node counter += 1 break def _create_node( self, func: Function, counter: int, variable: "Variable", scope: Union[Scope, Function] ): from slither.core.cfg.node import Node, NodeType from slither.core.expressions import ( AssignmentOperationType, AssignmentOperation, Identifier, ) # Function uses to create node for state variable declaration statements node = Node(NodeType.OTHER_ENTRYPOINT, counter, scope, func.file_scope) node.set_offset(variable.source_mapping, self.compilation_unit) node.set_function(func) func.add_node(node) assert variable.expression expression = AssignmentOperation( Identifier(variable), variable.expression, AssignmentOperationType.ASSIGN, variable.type, ) expression.set_offset(variable.source_mapping, self.compilation_unit) node.add_expression(expression) return node # endregion ################################################################################### ################################################################################### # region SlithIR ################################################################################### ################################################################################### def convert_expression_to_slithir_ssa(self): """ Assume generate_slithir_and_analyze was called on all functions :return: """ from slither.slithir.variables import StateIRVariable all_ssa_state_variables_instances = {} for contract in self.inheritance: for v in contract.state_variables_declared: new_var = StateIRVariable(v) all_ssa_state_variables_instances[v.canonical_name] = new_var self._initial_state_variables.append(new_var) for v in self.variables: if v.contract == self: new_var = StateIRVariable(v) all_ssa_state_variables_instances[v.canonical_name] = new_var self._initial_state_variables.append(new_var) for func in self.functions + self.modifiers: func.generate_slithir_ssa(all_ssa_state_variables_instances) def fix_phi(self): last_state_variables_instances = {} initial_state_variables_instances = {} for v in self._initial_state_variables: last_state_variables_instances[v.canonical_name] = [] initial_state_variables_instances[v.canonical_name] = v for func in self.functions + self.modifiers: result = func.get_last_ssa_state_variables_instances() for variable_name, instances in result.items(): last_state_variables_instances[variable_name] += instances for func in self.functions + self.modifiers: func.fix_phi(last_state_variables_instances, initial_state_variables_instances) # endregion ################################################################################### ################################################################################### # region Built in definitions ################################################################################### ################################################################################### def __eq__(self, other): if isinstance(other, str): return other == self.name return NotImplemented def __neq__(self, other): if isinstance(other, str): return other != self.name return NotImplemented def __str__(self): return self.name def __hash__(self): return self._id # endregion
58,101
Python
.py
1,264
36.173259
118
0.535287
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,305
custom_error_contract.py
NioTheFirst_ScType/slither/core/declarations/custom_error_contract.py
from slither.core.children.child_contract import ChildContract from slither.core.declarations.custom_error import CustomError class CustomErrorContract(CustomError, ChildContract): def is_declared_by(self, contract): """ Check if the element is declared by the contract :param contract: :return: """ return self.contract == contract
387
Python
.py
10
32.3
62
0.72
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,306
function_top_level.py
NioTheFirst_ScType/slither/core/declarations/function_top_level.py
""" Function module """ from typing import List, Tuple, TYPE_CHECKING from slither.core.declarations import Function 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 FunctionTopLevel(Function, TopLevel): def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope"): super().__init__(compilation_unit) self._scope: "FileScope" = scope @property def file_scope(self) -> "FileScope": return self._scope @property def canonical_name(self) -> str: """ str: contract.func_name(type1,type2) Return the function signature without the return values """ if self._canonical_name is None: name, parameters, _ = self.signature self._canonical_name = ( ".".join(self._internal_scope + [name]) + "(" + ",".join(parameters) + ")" ) return self._canonical_name # endregion ################################################################################### ################################################################################### # region Functions ################################################################################### ################################################################################### @property def functions_shadowed(self) -> List["Function"]: return [] # endregion ################################################################################### ################################################################################### # region Summary information ################################################################################### ################################################################################### def get_summary( self, ) -> Tuple[str, str, str, List[str], List[str], List[str], List[str], List[str]]: """ Return the function summary Returns: (str, str, str, list(str), list(str), listr(str), list(str), list(str); contract_name, name, visibility, modifiers, vars read, vars written, internal_calls, external_calls_as_expressions """ return ( "", self.full_name, self.visibility, [str(x) for x in self.modifiers], [str(x) for x in self.state_variables_read + self.solidity_variables_read], [str(x) for x in self.state_variables_written], [str(x) for x in self.internal_calls], [str(x) for x in self.external_calls_as_expressions], ) # endregion ################################################################################### ################################################################################### # region SlithIr and SSA ################################################################################### ################################################################################### def generate_slithir_ssa(self, all_ssa_state_variables_instances): # pylint: disable=import-outside-toplevel from slither.slithir.utils.ssa import add_ssa_ir, transform_slithir_vars_to_ssa from slither.core.dominators.utils import ( compute_dominance_frontier, compute_dominators, ) compute_dominators(self.nodes) compute_dominance_frontier(self.nodes) transform_slithir_vars_to_ssa(self) add_ssa_ir(self, all_ssa_state_variables_instances)
3,712
Python
.py
79
39.177215
126
0.450124
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,307
convert.py
NioTheFirst_ScType/slither/slithir/convert.py
import logging from pathlib import Path from typing import List, TYPE_CHECKING, Union, Optional # pylint: disable= too-many-lines,import-outside-toplevel,too-many-branches,too-many-statements,too-many-nested-blocks from slither.core.declarations import ( Contract, Enum, Event, Function, SolidityFunction, SolidityVariable, SolidityVariableComposed, Structure, ) from slither.core.declarations.custom_error import CustomError from slither.core.declarations.function_contract import FunctionContract from slither.core.declarations.function_top_level import FunctionTopLevel from slither.core.declarations.solidity_import_placeholder import SolidityImportPlaceHolder from slither.core.declarations.solidity_variables import SolidityCustomRevert from slither.core.expressions import Identifier, Literal from slither.core.solidity_types import ( ArrayType, ElementaryType, FunctionType, MappingType, UserDefinedType, TypeInformation, ) from slither.core.solidity_types.elementary_type import ( Int as ElementaryTypeInt, Uint, Byte, MaxValues, ) from slither.core.solidity_types.type import Type from slither.core.solidity_types.type_alias import TypeAlias from slither.core.variables.function_type_variable import FunctionTypeVariable from slither.core.variables.state_variable import StateVariable from slither.core.variables.variable import Variable from slither.slithir.exceptions import SlithIRError from slither.slithir.operations import ( Assignment, Binary, BinaryType, Call, Condition, Delete, EventCall, HighLevelCall, Index, InitArray, InternalCall, InternalDynamicCall, Length, LibraryCall, LowLevelCall, Member, NewArray, NewContract, NewElementaryType, NewStructure, OperationWithLValue, Return, Send, SolidityCall, Transfer, TypeConversion, Unary, Unpack, Nop, Operation, ) from slither.slithir.operations.codesize import CodeSize from slither.slithir.tmp_operations.argument import Argument, ArgumentType from slither.slithir.tmp_operations.tmp_call import TmpCall from slither.slithir.tmp_operations.tmp_new_array import TmpNewArray from slither.slithir.tmp_operations.tmp_new_contract import TmpNewContract from slither.slithir.tmp_operations.tmp_new_elementary_type import TmpNewElementaryType from slither.slithir.tmp_operations.tmp_new_structure import TmpNewStructure from slither.slithir.variables import Constant, ReferenceVariable, TemporaryVariable from slither.slithir.variables import TupleVariable from slither.utils.function import get_function_id from slither.utils.type import export_nested_types_from_variable from slither.visitors.slithir.expression_to_slithir import ExpressionToSlithIR if TYPE_CHECKING: from slither.core.cfg.node import Node from slither.core.compilation_unit import SlitherCompilationUnit logger = logging.getLogger("ConvertToIR") def convert_expression(expression, node): # handle standlone expression # such as return true; from slither.core.cfg.node import NodeType if isinstance(expression, Literal) and node.type in [NodeType.IF, NodeType.IFLOOP]: cst = Constant(expression.value, expression.type) cond = Condition(cst) cond.set_expression(expression) cond.set_node(node) result = [cond] return result if isinstance(expression, Identifier) and node.type in [ NodeType.IF, NodeType.IFLOOP, ]: cond = Condition(expression.value) cond.set_expression(expression) cond.set_node(node) result = [cond] return result visitor = ExpressionToSlithIR(expression, node) result = visitor.result() result = apply_ir_heuristics(result, node) if result: if node.type in [NodeType.IF, NodeType.IFLOOP]: assert isinstance(result[-1], (OperationWithLValue)) cond = Condition(result[-1].lvalue) cond.set_expression(expression) cond.set_node(node) result.append(cond) elif node.type == NodeType.RETURN: # May return None if isinstance(result[-1], (OperationWithLValue)): r = Return(result[-1].lvalue) r.set_expression(expression) r.set_node(node) result.append(r) return result ################################################################################### ################################################################################### # region Helpers ################################################################################### ################################################################################### def is_value(ins): if isinstance(ins, TmpCall): if isinstance(ins.ori, Member): if ins.ori.variable_right == "value": return True return False def is_gas(ins): if isinstance(ins, TmpCall): if isinstance(ins.ori, Member): if ins.ori.variable_right == "gas": return True return False def _fits_under_integer(val: int, can_be_int: bool, can_be_uint) -> List[str]: """ Return the list of uint/int that can contain val :param val: :return: """ ret: List[str] = [] n = 8 assert can_be_int | can_be_uint while n <= 256: if can_be_uint: if val <= 2**n - 1: ret.append(f"uint{n}") if can_be_int: if val <= (2**n) / 2 - 1: ret.append(f"int{n}") n = n + 8 return ret def _fits_under_byte(val: Union[int, str]) -> List[str]: """ Return the list of byte that can contain val :param val: :return: """ # If the value is written as an int, it can only be saved in one byte size # If its a string, it can be fitted under multiple values if isinstance(val, int): hex_val = hex(val)[2:] size = len(hex_val) // 2 return [f"bytes{size}"] # val is a str length = len(val.encode("utf-8")) return [f"bytes{f}" for f in range(length, 33)] + ["bytes"] def _find_function_from_parameter( arguments: List[Variable], candidates: List[Function], full_comparison: bool ) -> Optional[Function]: """ Look for a function in candidates that can be the target based on the ir's call arguments Try the implicit type conversion for uint/int/bytes. Constant values can be both uint/int While variables stick to their base type, but can changed the size. If full_comparison is True it will do a comparison of all the arguments regardless if the candidate remained is one. :param arguments: :param candidates: :param full_comparison: :return: """ type_args: List[str] for idx, arg in enumerate(arguments): if isinstance(arg, (list,)): type_args = [f"{get_type(arg[0].type)}[{len(arg)}]"] elif isinstance(arg, Function): type_args = [arg.signature_str] else: type_args = [get_type(arg.type)] arg_type = arg.type if isinstance( arg_type, ElementaryType ) and arg_type.type in ElementaryTypeInt + Uint + Byte + ["string"]: if isinstance(arg, Constant): value = arg.value can_be_uint = True can_be_int = True else: value = MaxValues[arg_type.type] can_be_uint = False can_be_int = False if arg_type.type in ElementaryTypeInt: can_be_int = True elif arg_type.type in Uint: can_be_uint = True if arg_type.type in ElementaryTypeInt + Uint: type_args = _fits_under_integer(value, can_be_int, can_be_uint) elif value is None and arg_type.type in ["bytes", "string"]: type_args = ["bytes", "string"] else: type_args = _fits_under_byte(value) if arg_type.type == "string": type_args += ["string"] not_found = True candidates_kept = [] for type_arg in type_args: if not not_found: break candidates_kept = [] for candidate in candidates: param = get_type(candidate.parameters[idx].type) if param == type_arg: not_found = False candidates_kept.append(candidate) if len(candidates_kept) == 1 and not full_comparison: return candidates_kept[0] candidates = candidates_kept if len(candidates) == 1: return candidates[0] return None def is_temporary(ins): return isinstance( ins, (Argument, TmpNewElementaryType, TmpNewContract, TmpNewArray, TmpNewStructure), ) def _make_function_type(func: Function) -> FunctionType: parameters = [] returns = [] for parameter in func.parameters: v = FunctionTypeVariable() v.name = parameter.name parameters.append(v) for return_var in func.returns: v = FunctionTypeVariable() v.name = return_var.name returns.append(v) return FunctionType(parameters, returns) # endregion ################################################################################### ################################################################################### # region Calls modification ################################################################################### ################################################################################### def integrate_value_gas(result): """ Integrate value and gas temporary arguments to call instruction """ was_changed = True calls = [] while was_changed: # We loop until we do not find any call to value or gas was_changed = False # Find all the assignments assigments = {} for i in result: if isinstance(i, OperationWithLValue): assigments[i.lvalue.name] = i if isinstance(i, TmpCall): if isinstance(i.called, Variable) and i.called.name in assigments: ins_ori = assigments[i.called.name] i.set_ori(ins_ori) to_remove = [] variable_to_replace = {} # Replace call to value, gas to an argument of the real call for idx, ins in enumerate(result): # value can be shadowed, so we check that the prev ins # is an Argument if is_value(ins) and isinstance(result[idx - 1], Argument): was_changed = True result[idx - 1].set_type(ArgumentType.VALUE) result[idx - 1].call_id = ins.ori.variable_left.name calls.append(ins.ori.variable_left) to_remove.append(ins) variable_to_replace[ins.lvalue.name] = ins.ori.variable_left elif is_gas(ins) and isinstance(result[idx - 1], Argument): was_changed = True result[idx - 1].set_type(ArgumentType.GAS) result[idx - 1].call_id = ins.ori.variable_left.name calls.append(ins.ori.variable_left) to_remove.append(ins) variable_to_replace[ins.lvalue.name] = ins.ori.variable_left # Remove the call to value/gas instruction result = [i for i in result if not i in to_remove] # update the real call for ins in result: if isinstance(ins, TmpCall): # use of while if there redirections while ins.called.name in variable_to_replace: was_changed = True ins.call_id = variable_to_replace[ins.called.name].name calls.append(ins.called) ins.called = variable_to_replace[ins.called.name] if isinstance(ins, Argument): while ins.call_id in variable_to_replace: was_changed = True ins.call_id = variable_to_replace[ins.call_id].name calls = list({str(c) for c in calls}) idx = 0 calls_d = {} for call in calls: calls_d[str(call)] = idx idx = idx + 1 return result # endregion ################################################################################### ################################################################################### # region Calls modification and Type propagation ################################################################################### ################################################################################### def propagate_type_and_convert_call(result: List[Operation], node: "Node") -> List[Operation]: """ Propagate the types variables and convert tmp call to real call operation """ calls_value = {} calls_gas = {} call_data = [] idx = 0 # use of while len() as result can be modified during the iteration while idx < len(result): ins = result[idx] if isinstance(ins, TmpCall): # If the node.function is a FunctionTopLevel, then it does not have a contract contract = ( node.function.contract if isinstance(node.function, FunctionContract) else None ) new_ins = extract_tmp_call(ins, contract) if new_ins: new_ins.set_node(ins.node) ins = new_ins result[idx] = ins # If there's two consecutive type conversions, keep only the last # ARG_CALL x call_data = [x] # TMP_4 = CONVERT x to Fix call_data = [] # TMP_5 = CONVERT TMP_4 to uint192 call_data = [TMP_5] if isinstance(ins, TypeConversion) and ins.variable in call_data: call_data.remove(ins.variable) if isinstance(ins, Argument): # In case of dupplicate arguments we overwrite the value # This can happen because of addr.call.value(1).value(2) if ins.get_type() in [ArgumentType.GAS]: calls_gas[ins.call_id] = ins.argument elif ins.get_type() in [ArgumentType.VALUE]: calls_value[ins.call_id] = ins.argument else: assert ins.get_type() == ArgumentType.CALL call_data.append(ins.argument) if isinstance(ins, (HighLevelCall, NewContract, InternalDynamicCall)): if ins.call_id in calls_value: ins.call_value = calls_value[ins.call_id] if ins.call_id in calls_gas: ins.call_gas = calls_gas[ins.call_id] if isinstance(ins, (Call, NewContract, NewStructure)): # We might have stored some arguments for libraries if ins.arguments: call_data = ins.arguments + call_data ins.arguments = call_data call_data = [] if is_temporary(ins): del result[idx] continue new_ins = propagate_types(ins, node) if new_ins: if isinstance(new_ins, (list,)): for new_ins_ in new_ins: new_ins_.set_node(ins.node) del result[idx] for i, ins in enumerate(new_ins): result.insert(idx + i, ins) idx = idx + len(new_ins) - 1 else: new_ins.set_node(ins.node) result[idx] = new_ins idx = idx + 1 return result def _convert_type_contract(ir: Member) -> Assignment: assert isinstance(ir.variable_left.type, TypeInformation) contract = ir.variable_left.type.type scope = ir.node.file_scope if ir.variable_right == "creationCode": bytecode = scope.bytecode_init( ir.node.compilation_unit.crytic_compile_compilation_unit, contract.name ) assignment = Assignment(ir.lvalue, Constant(str(bytecode)), ElementaryType("bytes")) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("bytes")) return assignment if ir.variable_right == "runtimeCode": bytecode = scope.bytecode_runtime( ir.node.compilation_unit.crytic_compile_compilation_unit, contract.name ) assignment = Assignment(ir.lvalue, Constant(str(bytecode)), ElementaryType("bytes")) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("bytes")) return assignment if ir.variable_right == "interfaceId": entry_points = contract.functions_entry_points interfaceId = 0 for entry_point in entry_points: interfaceId = interfaceId ^ get_function_id(entry_point.full_name) assignment = Assignment( ir.lvalue, Constant(str(interfaceId), constant_type=ElementaryType("bytes4")), ElementaryType("bytes4"), ) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("bytes4")) return assignment if ir.variable_right == "name": assignment = Assignment(ir.lvalue, Constant(contract.name), ElementaryType("string")) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("string")) return assignment raise SlithIRError(f"type({contract.name}).{ir.variable_right} is unknown") def propagate_types(ir, node: "Node"): # pylint: disable=too-many-locals # propagate the type node_function = node.function using_for = ( node_function.contract.using_for_complete if isinstance(node_function, FunctionContract) else {} ) if isinstance(ir, OperationWithLValue): # Force assignment in case of missing previous correct type if not ir.lvalue.type: if isinstance(ir, Assignment): ir.lvalue.set_type(ir.rvalue.type) elif isinstance(ir, Binary): if BinaryType.return_bool(ir.type): ir.lvalue.set_type(ElementaryType("bool")) else: ir.lvalue.set_type(ir.variable_left.type) elif isinstance(ir, Delete): # nothing to propagate pass elif isinstance(ir, LibraryCall): return convert_type_library_call(ir, ir.destination) elif isinstance(ir, HighLevelCall): t = ir.destination.type # Temporary operation (they are removed later) if t is None: return None if isinstance(t, ElementaryType) and t.name == "address": if can_be_solidity_func(ir): return convert_to_solidity_func(ir) # convert library or top level function if t in using_for or "*" in using_for: new_ir = convert_to_library_or_top_level(ir, node, using_for) if new_ir: return new_ir if isinstance(t, UserDefinedType): # UserdefinedType t_type = t.type if isinstance(t_type, Contract): # the target contract of the IR is the t_type (the destination of the call) return convert_type_of_high_and_internal_level_call(ir, t_type) # Convert HighLevelCall to LowLevelCall if (isinstance(t, ElementaryType) and t.name == "address") or ( isinstance(t, TypeAlias) and t.underlying_type.name == "address" ): # Cannot be a top level function with this. assert isinstance(node_function, FunctionContract) if ir.destination.name == "this": # the target contract is the contract itself return convert_type_of_high_and_internal_level_call( ir, node_function.contract ) if can_be_low_level(ir): return convert_to_low_level(ir) # Convert push operations # May need to insert a new operation # Which leads to return a list of operation if isinstance(t, ArrayType) or ( isinstance(t, ElementaryType) and t.type == "bytes" ): if ir.function_name == "push" and len(ir.arguments) <= 1: return convert_to_push(ir, node) if ir.function_name == "pop" and len(ir.arguments) == 0: return convert_to_pop(ir, node) elif isinstance(ir, Index): if isinstance(ir.variable_left.type, MappingType): ir.lvalue.set_type(ir.variable_left.type.type_to) elif isinstance(ir.variable_left.type, ArrayType): ir.lvalue.set_type(ir.variable_left.type.type) elif isinstance(ir, InitArray): length = len(ir.init_values) t = ir.init_values[0].type ir.lvalue.set_type(ArrayType(t, length)) elif isinstance(ir, InternalCall): # if its not a tuple, return a singleton if ir.function is None: func = node.function function_contract = ( func.contract if isinstance(func, FunctionContract) else None ) # the target contract might be None if its a top level function convert_type_of_high_and_internal_level_call(ir, function_contract) return_type = ir.function.return_type if return_type: if len(return_type) == 1: ir.lvalue.set_type(return_type[0]) elif len(return_type) > 1: ir.lvalue.set_type(return_type) else: ir.lvalue = None elif isinstance(ir, InternalDynamicCall): # if its not a tuple, return a singleton return_type = ir.function_type.return_type if return_type: if len(return_type) == 1: ir.lvalue.set_type(return_type[0]) else: ir.lvalue.set_type(return_type) else: ir.lvalue = None elif isinstance(ir, LowLevelCall): # Call are not yet converted # This should not happen assert False elif isinstance(ir, Member): # TODO we should convert the reference to a temporary if the member is a length or a balance if ( ir.variable_right == "length" and not isinstance(ir.variable_left, Contract) and isinstance(ir.variable_left.type, (ElementaryType, ArrayType)) ): length = Length(ir.variable_left, ir.lvalue) length.set_expression(ir.expression) length.lvalue.points_to = ir.variable_left length.set_node(ir.node) return length # This only happen for .balance/code/codehash access on a variable for which we dont know at # early parsing time the type # Like # function return_addr() internal returns(addresss) # # return_addr().balance # Here slithIR will incorrectly create a REF variable instead of a Temp variable # However this pattern does not appear so often if ( ir.variable_right.name in ["balance", "code", "codehash"] and not isinstance(ir.variable_left, Contract) and isinstance(ir.variable_left.type, ElementaryType) ): name = ir.variable_right.name + "(address)" sol_func = SolidityFunction(name) s = SolidityCall( sol_func, 1, ir.lvalue, sol_func.return_type, ) s.arguments.append(ir.variable_left) s.set_expression(ir.expression) s.lvalue.set_type(sol_func.return_type) s.set_node(ir.node) return s if ( ir.variable_right == "codesize" and not isinstance(ir.variable_left, Contract) and isinstance(ir.variable_left.type, ElementaryType) ): b = CodeSize(ir.variable_left, ir.lvalue) b.set_expression(ir.expression) b.set_node(ir.node) return b if ir.variable_right == "selector" and isinstance(ir.variable_left, (CustomError)): assignment = Assignment( ir.lvalue, Constant( str(get_function_id(ir.variable_left.solidity_signature)), ElementaryType("bytes4"), ), ElementaryType("bytes4"), ) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("bytes4")) return assignment if isinstance(ir.variable_right, (CustomError)): assignment = Assignment( ir.lvalue, Constant( str(get_function_id(ir.variable_left.solidity_signature)), ElementaryType("bytes4"), ), ElementaryType("bytes4"), ) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("bytes4")) return assignment if ir.variable_right == "selector" and isinstance( ir.variable_left.type, (Function) ): assignment = Assignment( ir.lvalue, Constant(str(get_function_id(ir.variable_left.type.full_name))), ElementaryType("bytes4"), ) assignment.set_expression(ir.expression) assignment.set_node(ir.node) assignment.lvalue.set_type(ElementaryType("bytes4")) return assignment if isinstance(ir.variable_left, TemporaryVariable) and isinstance( ir.variable_left.type, TypeInformation ): return _convert_type_contract(ir) left = ir.variable_left t = None ir_func = ir.function # Handling of this.function_name usage if ( left == SolidityVariable("this") and isinstance(ir.variable_right, Constant) and isinstance(ir_func, FunctionContract) and str(ir.variable_right) in [x.name for x in ir_func.contract.functions] ): # Assumption that this.function_name can only compile if # And the contract does not have two functions starting with function_name # Otherwise solc raises: # Error: Member "f" not unique after argument-dependent lookup in contract targeted_function = next( (x for x in ir_func.contract.functions if x.name == str(ir.variable_right)) ) t = _make_function_type(targeted_function) ir.lvalue.set_type(t) elif isinstance(left, (Variable, SolidityVariable)): t = ir.variable_left.type elif isinstance(left, (Contract, Enum, Structure)): t = UserDefinedType(left) # can be None due to temporary operation if t: if isinstance(t, UserDefinedType): # UserdefinedType type_t = t.type if isinstance(type_t, Enum): ir.lvalue.set_type(t) elif isinstance(type_t, Structure): elems = type_t.elems for elem in elems: if elem == ir.variable_right: ir.lvalue.set_type(elems[elem].type) else: assert isinstance(type_t, Contract) # Allow type propagtion as a Function # Only for reference variables # This allows to track the selector keyword # We dont need to check for function collision, as solc prevents the use of selector # if there are multiple functions with the same name f = next( (f for f in type_t.functions if f.name == ir.variable_right), None, ) if f: ir.lvalue.set_type(f) else: # Allow propgation for variable access through contract's name # like Base_contract.my_variable v = next( ( v for v in type_t.state_variables if v.name == ir.variable_right ), None, ) if v: ir.lvalue.set_type(v.type) elif isinstance(ir, NewArray): ir.lvalue.set_type(ir.array_type) elif isinstance(ir, NewContract): contract = node.file_scope.get_contract_from_name(ir.contract_name) ir.lvalue.set_type(UserDefinedType(contract)) elif isinstance(ir, NewElementaryType): ir.lvalue.set_type(ir.type) elif isinstance(ir, NewStructure): ir.lvalue.set_type(UserDefinedType(ir.structure)) elif isinstance(ir, Send): ir.lvalue.set_type(ElementaryType("bool")) elif isinstance(ir, SolidityCall): if ir.function.name in ["type(address)", "type()"]: ir.function.return_type = [TypeInformation(ir.arguments[0])] return_type = ir.function.return_type if len(return_type) == 1: ir.lvalue.set_type(return_type[0]) elif len(return_type) > 1: ir.lvalue.set_type(return_type) elif isinstance(ir, TypeConversion): ir.lvalue.set_type(ir.type) elif isinstance(ir, Unary): ir.lvalue.set_type(ir.rvalue.type) elif isinstance(ir, Unpack): types = ir.tuple.type.type idx = ir.index t = types[idx] ir.lvalue.set_type(t) elif isinstance( ir, ( Argument, TmpCall, TmpNewArray, TmpNewContract, TmpNewStructure, TmpNewElementaryType, ), ): # temporary operation; they will be removed pass else: raise SlithIRError(f"Not handling {type(ir)} during type propagation") return None def extract_tmp_call(ins: TmpCall, contract: Optional[Contract]): # pylint: disable=too-many-locals assert isinstance(ins, TmpCall) if isinstance(ins.called, Variable) and isinstance(ins.called.type, FunctionType): # If the call is made to a variable member, where the member is this # We need to convert it to a HighLelelCall and not an internal dynamic call if isinstance(ins.ori, Member) and ins.ori.variable_left == SolidityVariable("this"): pass else: call = InternalDynamicCall(ins.lvalue, ins.called, ins.called.type) call.set_expression(ins.expression) call.call_id = ins.call_id return call if isinstance(ins.ori, Member): # If there is a call on an inherited contract, it is an internal call or an event if contract and ins.ori.variable_left in contract.inheritance + [contract]: if str(ins.ori.variable_right) in [f.name for f in contract.functions]: internalcall = InternalCall( (ins.ori.variable_right, ins.ori.variable_left.name), ins.nbr_arguments, ins.lvalue, ins.type_call, ) internalcall.set_expression(ins.expression) internalcall.call_id = ins.call_id return internalcall if str(ins.ori.variable_right) in [f.name for f in contract.events]: eventcall = EventCall(ins.ori.variable_right) eventcall.set_expression(ins.expression) eventcall.call_id = ins.call_id return eventcall if isinstance(ins.ori.variable_left, Contract): st = ins.ori.variable_left.get_structure_from_name(ins.ori.variable_right) if st: op = NewStructure(st, ins.lvalue) op.set_expression(ins.expression) op.call_id = ins.call_id return op # For event emit through library # lib L { event E()} # ... # emit L.E(); if str(ins.ori.variable_right) in [f.name for f in ins.ori.variable_left.events]: eventcall = EventCall(ins.ori.variable_right) eventcall.set_expression(ins.expression) eventcall.call_id = ins.call_id return eventcall # lib Lib { error Error()} ... revert Lib.Error() if str(ins.ori.variable_right) in ins.ori.variable_left.custom_errors_as_dict: custom_error = ins.ori.variable_left.custom_errors_as_dict[ str(ins.ori.variable_right) ] assert isinstance( custom_error, CustomError, ) sol_function = SolidityCustomRevert(custom_error) solidity_call = SolidityCall( sol_function, ins.nbr_arguments, ins.lvalue, ins.type_call ) solidity_call.set_expression(ins.expression) return solidity_call libcall = LibraryCall( ins.ori.variable_left, ins.ori.variable_right, ins.nbr_arguments, ins.lvalue, ins.type_call, ) libcall.set_expression(ins.expression) libcall.call_id = ins.call_id return libcall if isinstance(ins.ori.variable_left, Function): # Support for library call where the parameter is a function # We could merge this with the standard library handling # Except that we will have some troubles with using_for # As the type of the funciton will not match function() # Additionally we do not have a correct view on the parameters of the tmpcall # At this level # # library FunctionExtensions { # function h(function() internal _t, uint8) internal { } # } # contract FunctionMembers { # using FunctionExtensions for function(); # # function f() public { # f.h(1); # } # } node_func = ins.node.function using_for = ( node_func.contract.using_for_complete if isinstance(node_func, FunctionContract) else {} ) targeted_libraries = ( [] + using_for.get("*", []) + using_for.get(FunctionType([], []), []) ) lib_contract: Contract candidates = [] for lib_contract_type in targeted_libraries: if not isinstance(lib_contract_type, UserDefinedType) and isinstance( lib_contract_type.type, Contract ): continue if isinstance(lib_contract_type, FunctionContract): # Using for with list of functions, this is the function called candidates.append(lib_contract_type) else: lib_contract = lib_contract_type.type for lib_func in lib_contract.functions: if lib_func.name == ins.ori.variable_right: candidates.append(lib_func) if len(candidates) == 1: lib_func = candidates[0] # Library must be from a contract assert isinstance(lib_func, FunctionContract) lib_call = LibraryCall( lib_func.contract, Constant(lib_func.name), len(lib_func.parameters), ins.lvalue, "d", ) lib_call.set_expression(ins.expression) lib_call.set_node(ins.node) lib_call.call_gas = ins.call_gas lib_call.call_id = ins.call_id lib_call.set_node(ins.node) lib_call.function = lib_func lib_call.arguments.append(ins.ori.variable_left) return lib_call # We do not support something lik # library FunctionExtensions { # function h(function() internal _t, uint8) internal { } # function h(function() internal _t, bool) internal { } # } # contract FunctionMembers { # using FunctionExtensions for function(); # # function f() public { # f.h(1); # } # } to_log = "Slither does not support dynamic functions to libraries if functions have the same name" to_log += f"{[candidate.full_name for candidate in candidates]}" raise SlithIRError(to_log) if isinstance(ins.ori.variable_left, SolidityImportPlaceHolder): # For top level import, where the import statement renames the filename # See https://blog.soliditylang.org/2020/09/02/solidity-0.7.1-release-announcement/ current_path = Path(ins.ori.variable_left.source_mapping.filename.absolute).parent target = str( Path(current_path, ins.ori.variable_left.import_directive.filename).absolute() ) top_level_function_targets = [ f for f in ins.compilation_unit.functions_top_level if f.source_mapping.filename.absolute == target and f.name == ins.ori.variable_right and len(f.parameters) == ins.nbr_arguments ] internalcall = InternalCall( (ins.ori.variable_right, ins.ori.variable_left.name), ins.nbr_arguments, ins.lvalue, ins.type_call, ) internalcall.set_expression(ins.expression) internalcall.call_id = ins.call_id internalcall.function_candidates = top_level_function_targets return internalcall if ins.ori.variable_left == ElementaryType("bytes") and ins.ori.variable_right == Constant( "concat" ): s = SolidityCall( SolidityFunction("bytes.concat()"), ins.nbr_arguments, ins.lvalue, ins.type_call, ) s.set_expression(ins.expression) return s if ins.ori.variable_left == ElementaryType("string") and ins.ori.variable_right == Constant( "concat" ): s = SolidityCall( SolidityFunction("string.concat()"), ins.nbr_arguments, ins.lvalue, ins.type_call, ) s.set_expression(ins.expression) return s msgcall = HighLevelCall( ins.ori.variable_left, ins.ori.variable_right, ins.nbr_arguments, ins.lvalue, ins.type_call, ) msgcall.call_id = ins.call_id if ins.call_gas: msgcall.call_gas = ins.call_gas if ins.call_value: msgcall.call_value = ins.call_value msgcall.set_expression(ins.expression) return msgcall if isinstance(ins.ori, TmpCall): r = extract_tmp_call(ins.ori, contract) r.set_node(ins.node) return r if isinstance(ins.called, SolidityVariableComposed): if str(ins.called) == "block.blockhash": ins.called = SolidityFunction("blockhash(uint256)") if isinstance(ins.called, SolidityFunction): s = SolidityCall(ins.called, ins.nbr_arguments, ins.lvalue, ins.type_call) s.set_expression(ins.expression) return s if isinstance(ins.called, CustomError): sol_function = SolidityCustomRevert(ins.called) s = SolidityCall(sol_function, ins.nbr_arguments, ins.lvalue, ins.type_call) s.set_expression(ins.expression) return s if isinstance(ins.ori, TmpNewElementaryType): n = NewElementaryType(ins.ori.type, ins.lvalue) n.set_expression(ins.expression) return n if isinstance(ins.ori, TmpNewContract): op = NewContract(Constant(ins.ori.contract_name), ins.lvalue) op.set_expression(ins.expression) op.call_id = ins.call_id if ins.call_value: op.call_value = ins.call_value if ins.call_salt: op.call_salt = ins.call_salt return op if isinstance(ins.ori, TmpNewArray): n = NewArray(ins.ori.depth, ins.ori.array_type, ins.lvalue) n.set_expression(ins.expression) return n if isinstance(ins.called, Structure): op = NewStructure(ins.called, ins.lvalue) op.set_expression(ins.expression) op.call_id = ins.call_id op.set_expression(ins.expression) return op if isinstance(ins.called, Event): e = EventCall(ins.called.name) e.set_expression(ins.expression) return e if isinstance(ins.called, Contract): # Called a base constructor, where there is no constructor if ins.called.constructor is None: return Nop() # Case where: # contract A{ constructor(uint) } # contract B is A {} # contract C is B{ constructor() A(10) B() {} # C calls B(), which does not exist # Ideally we should compare here for the parameters types too if len(ins.called.constructor.parameters) != ins.nbr_arguments: return Nop() internalcall = InternalCall( ins.called.constructor, ins.nbr_arguments, ins.lvalue, ins.type_call ) internalcall.call_id = ins.call_id internalcall.set_expression(ins.expression) return internalcall raise Exception(f"Not extracted {type(ins.called)} {ins}") # endregion ################################################################################### ################################################################################### # region Conversion operations ################################################################################### ################################################################################### def can_be_low_level(ir): return ir.function_name in [ "transfer", "send", "call", "delegatecall", "callcode", "staticcall", ] def convert_to_low_level(ir): """ Convert to a transfer/send/or low level call The funciton assume to receive a correct IR The checks must be done by the caller Must be called after can_be_low_level """ if ir.function_name == "transfer": assert len(ir.arguments) == 1 prev_ir = ir ir = Transfer(ir.destination, ir.arguments[0]) ir.set_expression(prev_ir.expression) ir.set_node(prev_ir.node) return ir if ir.function_name == "send": assert len(ir.arguments) == 1 prev_ir = ir ir = Send(ir.destination, ir.arguments[0], ir.lvalue) ir.set_expression(prev_ir.expression) ir.set_node(prev_ir.node) ir.lvalue.set_type(ElementaryType("bool")) return ir if ir.function_name in ["call", "delegatecall", "callcode", "staticcall"]: new_ir = LowLevelCall( ir.destination, ir.function_name, ir.nbr_arguments, ir.lvalue, ir.type_call ) new_ir.call_gas = ir.call_gas new_ir.call_value = ir.call_value new_ir.arguments = ir.arguments if ir.node.compilation_unit.solc_version >= "0.5": new_ir.lvalue.set_type([ElementaryType("bool"), ElementaryType("bytes")]) else: new_ir.lvalue.set_type(ElementaryType("bool")) new_ir.set_expression(ir.expression) new_ir.set_node(ir.node) return new_ir raise SlithIRError(f"Incorrect conversion to low level {ir}") def can_be_solidity_func(ir) -> bool: if not isinstance(ir, HighLevelCall): return False return ir.destination.name == "abi" and ir.function_name in [ "encode", "encodePacked", "encodeWithSelector", "encodeWithSignature", "encodeCall", "decode", ] def convert_to_solidity_func(ir): """ Must be called after can_be_solidity_func :param ir: :return: """ call = SolidityFunction(f"abi.{ir.function_name}()") new_ir = SolidityCall(call, ir.nbr_arguments, ir.lvalue, ir.type_call) new_ir.arguments = ir.arguments new_ir.set_expression(ir.expression) new_ir.set_node(ir.node) if isinstance(call.return_type, list) and len(call.return_type) == 1: new_ir.lvalue.set_type(call.return_type[0]) elif ( isinstance(new_ir.lvalue, TupleVariable) and call == SolidityFunction("abi.decode()") and len(new_ir.arguments) == 2 and isinstance(new_ir.arguments[1], list) ): types = list(new_ir.arguments[1]) new_ir.lvalue.set_type(types) # abi.decode where the type to decode is a singleton # abi.decode(a, (uint)) elif call == SolidityFunction("abi.decode()") and len(new_ir.arguments) == 2: # If the variable is a referenceVariable, we are lost # See https://github.com/crytic/slither/issues/566 for potential solutions if not isinstance(new_ir.arguments[1], ReferenceVariable): decode_type = new_ir.arguments[1] if isinstance(decode_type, (Structure, Enum, Contract)): decode_type = UserDefinedType(decode_type) new_ir.lvalue.set_type(decode_type) else: new_ir.lvalue.set_type(call.return_type) return new_ir def convert_to_push_expand_arr(ir, node, ret): arr = ir.destination length = ReferenceVariable(node) length.set_type(ElementaryType("uint256")) ir_length = Length(arr, length) ir_length.set_expression(ir.expression) ir_length.set_node(ir.node) ir_length.lvalue.points_to = arr ret.append(ir_length) length_val = TemporaryVariable(node) length_val.set_type(ElementaryType("uint256")) ir_get_length = Assignment(length_val, length, ElementaryType("uint256")) ir_get_length.set_expression(ir.expression) ir_get_length.set_node(ir.node) ret.append(ir_get_length) new_length_val = TemporaryVariable(node) ir_add_1 = Binary( new_length_val, length_val, Constant("1", ElementaryType("uint256")), BinaryType.ADDITION ) ir_add_1.set_expression(ir.expression) ir_add_1.set_node(ir.node) ret.append(ir_add_1) ir_assign_length = Assignment(length, new_length_val, ElementaryType("uint256")) ir_assign_length.set_expression(ir.expression) ir_assign_length.set_node(ir.node) ret.append(ir_assign_length) return length_val def convert_to_push_set_val(ir, node, length_val, ret): arr = ir.destination new_type = ir.destination.type.type element_to_add = ReferenceVariable(node) element_to_add.set_type(new_type) ir_assign_element_to_add = Index(element_to_add, arr, length_val, ElementaryType("uint256")) ir_assign_element_to_add.set_expression(ir.expression) ir_assign_element_to_add.set_node(ir.node) ret.append(ir_assign_element_to_add) if len(ir.arguments) > 0: assign_value = ir.arguments[0] if isinstance(assign_value, list): assign_value = TemporaryVariable(node) assign_value.set_type(element_to_add.type) ir_assign_value = InitArray(ir.arguments[0], assign_value) ir_assign_value.set_expression(ir.expression) ir_assign_value.set_node(ir.node) ret.append(ir_assign_value) ir_assign_value = Assignment(element_to_add, assign_value, assign_value.type) ir_assign_value.set_expression(ir.expression) ir_assign_value.set_node(ir.node) ret.append(ir_assign_value) else: new_element = ir.lvalue new_element.set_type(new_type) ir_assign_value = Assignment(new_element, element_to_add, new_type) ir_assign_value.set_expression(ir.expression) ir_assign_value.set_node(ir.node) ret.append(ir_assign_value) def convert_to_push(ir, node): """ Convert a call to a series of operations to push a new value onto the array The function assume to receive a correct IR The checks must be done by the caller May necessitate to create an intermediate operation (InitArray) Necessitate to return the length (see push documentation) As a result, the function return may return a list """ ret = [] length_val = convert_to_push_expand_arr(ir, node, ret) convert_to_push_set_val(ir, node, length_val, ret) return ret def convert_to_pop(ir, node): """ Convert pop operators Return a list of 6 operations """ ret = [] arr = ir.destination length = ReferenceVariable(node) length.set_type(ElementaryType("uint256")) ir_length = Length(arr, length) ir_length.set_expression(ir.expression) ir_length.set_node(ir.node) ir_length.lvalue.points_to = arr ret.append(ir_length) val = TemporaryVariable(node) ir_sub_1 = Binary(val, length, Constant("1", ElementaryType("uint256")), BinaryType.SUBTRACTION) ir_sub_1.set_expression(ir.expression) ir_sub_1.set_node(ir.node) ret.append(ir_sub_1) element_to_delete = ReferenceVariable(node) ir_assign_element_to_delete = Index(element_to_delete, arr, val, ElementaryType("uint256")) ir_length.lvalue.points_to = arr element_to_delete.set_type(ElementaryType("uint256")) ir_assign_element_to_delete.set_expression(ir.expression) ir_assign_element_to_delete.set_node(ir.node) ret.append(ir_assign_element_to_delete) ir_delete = Delete(element_to_delete, element_to_delete) ir_delete.set_expression(ir.expression) ir_delete.set_node(ir.node) ret.append(ir_delete) length_to_assign = ReferenceVariable(node) length_to_assign.set_type(ElementaryType("uint256")) ir_length = Length(arr, length_to_assign) ir_length.set_expression(ir.expression) ir_length.lvalue.points_to = arr ir_length.set_node(ir.node) ret.append(ir_length) ir_assign_length = Assignment(length_to_assign, val, ElementaryType("uint256")) ir_assign_length.set_expression(ir.expression) ir_assign_length.set_node(ir.node) ret.append(ir_assign_length) return ret def look_for_library_or_top_level(contract, ir, using_for, t): for destination in using_for[t]: if isinstance(destination, FunctionTopLevel) and destination.name == ir.function_name: arguments = [ir.destination] + ir.arguments if ( len(destination.parameters) == len(arguments) and _find_function_from_parameter(arguments, [destination], True) is not None ): internalcall = InternalCall(destination, ir.nbr_arguments, ir.lvalue, ir.type_call) internalcall.set_expression(ir.expression) internalcall.set_node(ir.node) internalcall.arguments = [ir.destination] + ir.arguments return_type = internalcall.function.return_type if return_type: if len(return_type) == 1: internalcall.lvalue.set_type(return_type[0]) elif len(return_type) > 1: internalcall.lvalue.set_type(return_type) else: internalcall.lvalue = None return internalcall if isinstance(destination, FunctionContract) and destination.contract.is_library: lib_contract = destination.contract else: lib_contract = contract.file_scope.get_contract_from_name(str(destination)) if lib_contract: lib_call = LibraryCall( lib_contract, ir.function_name, ir.nbr_arguments, ir.lvalue, ir.type_call, ) lib_call.set_expression(ir.expression) lib_call.set_node(ir.node) lib_call.call_gas = ir.call_gas lib_call.arguments = [ir.destination] + ir.arguments new_ir = convert_type_library_call(lib_call, lib_contract) if new_ir: new_ir.set_node(ir.node) return new_ir return None def convert_to_library_or_top_level(ir, node, using_for): # We use contract_declarer, because Solidity resolve the library # before resolving the inheritance. # Though we could use .contract as libraries cannot be shadowed contract = node.function.contract_declarer t = ir.destination.type if t in using_for: new_ir = look_for_library_or_top_level(contract, ir, using_for, t) if new_ir: return new_ir if "*" in using_for: new_ir = look_for_library_or_top_level(contract, ir, using_for, "*") if new_ir: return new_ir return None def get_type(t): """ Convert a type to a str If the instance is a Contract, return 'address' instead """ if isinstance(t, UserDefinedType): if isinstance(t.type, Contract): return "address" return str(t) def _can_be_implicitly_converted(source: str, target: str) -> bool: if source in ElementaryTypeInt and target in ElementaryTypeInt: return int(source[3:]) <= int(target[3:]) if source in Uint and target in Uint: return int(source[4:]) <= int(target[4:]) return source == target def convert_type_library_call(ir: HighLevelCall, lib_contract: Contract): func = None candidates = [ f for f in lib_contract.functions if f.name == ir.function_name and not f.is_shadowed and len(f.parameters) == len(ir.arguments) ] if len(candidates) == 1: func = candidates[0] # We can discard if there are arguments here because libraries only support constant variables # And constant variables cannot have non-value type # i.e. "uint[2] constant arr = [1,2];" is not possible in Solidity # If this were to change, the following condition might be broken if func is None and not ir.arguments: # TODO: handle collision with multiple state variables/functions func = lib_contract.get_state_variable_from_name(ir.function_name) if func is None and candidates: func = _find_function_from_parameter(ir.arguments, candidates, False) # In case of multiple binding to the same type # TODO: this part might not be needed with _find_function_from_parameter if not func: # specific lookup when the compiler does implicit conversion # for example # myFunc(uint) # can be called with an uint8 for function in lib_contract.functions: if function.name == ir.function_name and len(function.parameters) == len(ir.arguments): func = function break if not func: return None ir.function = func if isinstance(func, Function): t = func.return_type # if its not a tuple, return a singleton if t and len(t) == 1: t = t[0] else: # otherwise its a variable (getter) t = func.type if t: ir.lvalue.set_type(t) else: ir.lvalue = None return ir def _convert_to_structure_to_list(return_type: Type) -> List[Type]: """ Convert structure elements types to a list of types Recursive function :param return_type: :return: """ if isinstance(return_type, UserDefinedType) and isinstance(return_type.type, Structure): ret = [] for v in return_type.type.elems_ordered: ret += _convert_to_structure_to_list(v.type) return ret # Mapping and arrays are not included in external call # # contract A{ # # struct St{ # uint a; # uint b; # mapping(uint => uint) map; # uint[] array; # } # # mapping (uint => St) public st; # # } # # contract B{ # # function f(A a) public{ # (uint a, uint b) = a.st(0); # } # } if isinstance(return_type, (MappingType, ArrayType)): return [] return [return_type.type] def convert_type_of_high_and_internal_level_call( ir: Operation, contract: Optional[Contract] ) -> Optional[Operation]: """ Convert the IR type based on heuristic Args: ir: target contract: optional contract. This should be the target of the IR. It will be used to look up potential functions Returns: Potential new IR """ func = None if isinstance(ir, InternalCall): candidates: List[Function] if ir.function_candidates: # This path is taken only for SolidityImportPlaceHolder # Here we have already done a filtering on the potential targets candidates = ir.function_candidates else: candidates = [ f for f in contract.functions if f.name == ir.function_name and f.contract_declarer.name == ir.contract_name and len(f.parameters) == len(ir.arguments) ] for import_statement in contract.file_scope.imports: if import_statement.alias and import_statement.alias == ir.contract_name: imported_scope = contract.compilation_unit.get_scope(import_statement.filename) candidates += [ f for f in list(imported_scope.functions) if f.name == ir.function_name and len(f.parameters) == len(ir.arguments) ] func = _find_function_from_parameter(ir.arguments, candidates, False) if not func: assert contract func = contract.get_state_variable_from_name(ir.function_name) else: assert isinstance(ir, HighLevelCall) assert contract candidates = [ f for f in contract.functions if f.name == ir.function_name and not f.is_shadowed and len(f.parameters) == len(ir.arguments) ] if len(candidates) == 1: func = candidates[0] if func is None: # TODO: handle collision with multiple state variables/functions func = contract.get_state_variable_from_name(ir.function_name) if func is None and candidates: func = _find_function_from_parameter(ir.arguments, candidates, False) # lowlelvel lookup needs to be done at last step if not func: if can_be_low_level(ir): return convert_to_low_level(ir) if can_be_solidity_func(ir): return convert_to_solidity_func(ir) if not func: to_log = f"Function not found {ir.function_name}" logger.error(to_log) ir.function = func if isinstance(func, Function): return_type = func.return_type # if its not a tuple; return a singleton if return_type and len(return_type) == 1: return_type = return_type[0] else: # otherwise its a variable (getter) # If its a mapping or a array # we iterate until we find the final type # mapping and array can be mixed together # ex: # mapping ( uint => mapping ( uint => uint)) my_var # mapping(uint => uint)[] test;p if isinstance(func.type, (MappingType, ArrayType)): tmp = func.type while isinstance(tmp, (MappingType, ArrayType)): if isinstance(tmp, MappingType): tmp = tmp.type_to else: tmp = tmp.type return_type = tmp else: return_type = func.type if return_type: # If the return type is a structure, but the lvalue is a tuple # We convert the type of the structure to a list of element # TODO: explore to replace all tuple variables by structures if ( isinstance(ir.lvalue, TupleVariable) and isinstance(return_type, UserDefinedType) and isinstance(return_type.type, Structure) ): return_type = _convert_to_structure_to_list(return_type) ir.lvalue.set_type(return_type) else: ir.lvalue = None return None # endregion ################################################################################### ################################################################################### # region Points to operation ################################################################################### ################################################################################### def find_references_origin(irs): """ Make lvalue of each Index, Member operation points to the left variable """ for ir in irs: if isinstance(ir, (Index, Member)): ir.lvalue.points_to = ir.variable_left # endregion ################################################################################### ################################################################################### # region Operation filtering ################################################################################### ################################################################################### def remove_temporary(result): result = [ ins for ins in result if not isinstance( ins, ( Argument, TmpNewElementaryType, TmpNewContract, TmpNewArray, TmpNewStructure, ), ) ] return result def remove_unused(result): removed = True if not result: return result # dont remove the last elem, as it may be used by RETURN last_elem = result[-1] while removed: removed = False to_keep = [] to_remove = [] # keep variables that are read # and reference that are written for ins in result: to_keep += [str(x) for x in ins.read] if isinstance(ins, OperationWithLValue) and not isinstance(ins, (Index, Member)): if isinstance(ins.lvalue, ReferenceVariable): to_keep += [str(ins.lvalue)] for ins in result: if isinstance(ins, Member): if not ins.lvalue.name in to_keep and ins != last_elem: to_remove.append(ins) removed = True # Remove type(X) if X is an elementary type # This assume that type(X) is only used with min/max # If Solidity introduces other operation, we might remove this removal if isinstance(ins, SolidityCall) and ins.function == SolidityFunction("type()"): if isinstance(ins.arguments[0], ElementaryType): to_remove.append(ins) result = [i for i in result if not i in to_remove] return result # endregion ################################################################################### ################################################################################### # region Constant type conversion ################################################################################### ################################################################################### def convert_constant_types(irs): """ late conversion of uint -> type for constant (Literal) :param irs: :return: """ # TODO: implement instances lookup for events, NewContract was_changed = True while was_changed: was_changed = False for ir in irs: if isinstance(ir, Assignment): if isinstance(ir.lvalue.type, ElementaryType): if ir.lvalue.type.type in ElementaryTypeInt: if isinstance(ir.rvalue, Function): continue if isinstance(ir.rvalue, TupleVariable): # TODO: fix missing Unpack conversion continue if isinstance(ir.rvalue.type, TypeAlias): ir.rvalue.set_type(ElementaryType(ir.lvalue.type.name)) was_changed = True elif ir.rvalue.type.type not in ElementaryTypeInt: ir.rvalue.set_type(ElementaryType(ir.lvalue.type.type)) was_changed = True if isinstance(ir, Binary): if isinstance(ir.lvalue.type, ElementaryType): if ir.lvalue.type.type in ElementaryTypeInt: for r in ir.read: if r.type.type not in ElementaryTypeInt: r.set_type(ElementaryType(ir.lvalue.type.type)) was_changed = True if isinstance(ir, (HighLevelCall, InternalCall)): func = ir.function if isinstance(func, StateVariable): types = export_nested_types_from_variable(func) else: if func is None: # TODO: add POP instruction break types = [p.type for p in func.parameters] assert len(types) == len(ir.arguments) for idx, arg in enumerate(ir.arguments): t = types[idx] if isinstance(t, ElementaryType): if t.type in ElementaryTypeInt: if arg.type.type not in ElementaryTypeInt: arg.set_type(ElementaryType(t.type)) was_changed = True if isinstance(ir, NewStructure): st = ir.structure for idx, arg in enumerate(ir.arguments): e = st.elems_ordered[idx] if isinstance(e.type, ElementaryType): if e.type.type in ElementaryTypeInt: if arg.type.type not in ElementaryTypeInt: arg.set_type(ElementaryType(e.type.type)) was_changed = True if isinstance(ir, InitArray): if isinstance(ir.lvalue.type, ArrayType): if isinstance(ir.lvalue.type.type, ElementaryType): if ir.lvalue.type.type.type in ElementaryTypeInt: for r in ir.read: if r.type.type not in ElementaryTypeInt: r.set_type(ElementaryType(ir.lvalue.type.type.type)) was_changed = True # endregion ################################################################################### ################################################################################### # region Delete handling ################################################################################### ################################################################################### def convert_delete(irs): """ Convert the lvalue of the Delete to point to the variable removed This can only be done after find_references_origin is called :param irs: :return: """ for ir in irs: if isinstance(ir, Delete): if isinstance(ir.lvalue, ReferenceVariable): ir.lvalue = ir.lvalue.points_to # endregion ################################################################################### ################################################################################### # region Source Mapping ################################################################################### ################################################################################### def _find_source_mapping_references(irs: List[Operation]): for ir in irs: if isinstance(ir, NewContract): ir.contract_created.references.append(ir.expression.source_mapping) # endregion ################################################################################### ################################################################################### # region Heuristics selection ################################################################################### ################################################################################### def apply_ir_heuristics(irs: List[Operation], node: "Node"): """ Apply a set of heuristic to improve slithIR """ irs = integrate_value_gas(irs) irs = propagate_type_and_convert_call(irs, node) irs = remove_unused(irs) find_references_origin(irs) convert_constant_types(irs) convert_delete(irs) _find_source_mapping_references(irs) return irs
72,250
Python
.py
1,652
31.905569
120
0.551347
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,308
tmp_new_elementary_type.py
NioTheFirst_ScType/slither/slithir/tmp_operations/tmp_new_elementary_type.py
from typing import List from slither.slithir.operations.lvalue import OperationWithLValue from slither.core.solidity_types.elementary_type import ElementaryType class TmpNewElementaryType(OperationWithLValue): def __init__(self, new_type: ElementaryType, lvalue): assert isinstance(new_type, ElementaryType) super().__init__() self._type: ElementaryType = new_type self._lvalue = lvalue @property def read(self) -> List: return [] @property def type(self) -> ElementaryType: return self._type def __str__(self) -> str: return f"{self.lvalue} = new {self._type}"
648
Python
.py
17
32.058824
70
0.6896
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,309
tmp_new_array.py
NioTheFirst_ScType/slither/slithir/tmp_operations/tmp_new_array.py
from slither.slithir.operations.lvalue import OperationWithLValue from slither.core.solidity_types.type import Type class TmpNewArray(OperationWithLValue): def __init__(self, depth, array_type, lvalue): super().__init__() assert isinstance(array_type, Type) self._depth = depth self._array_type = array_type self._lvalue = lvalue @property def array_type(self): return self._array_type @property def read(self): return [] @property def depth(self): return self._depth def __str__(self): return f"{self.lvalue} = new {self.array_type}{'[]' * self._depth}"
665
Python
.py
20
26.75
75
0.644757
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,310
tmp_new_contract.py
NioTheFirst_ScType/slither/slithir/tmp_operations/tmp_new_contract.py
from slither.slithir.operations.lvalue import OperationWithLValue class TmpNewContract(OperationWithLValue): def __init__(self, contract_name, lvalue): super().__init__() self._contract_name = contract_name self._lvalue = lvalue self._call_value = None self._call_salt = None @property def contract_name(self): return self._contract_name @property def call_value(self): return self._call_value @call_value.setter def call_value(self, v): self._call_value = v @property def call_salt(self): return self._call_salt @call_salt.setter def call_salt(self, s): self._call_salt = s @property def read(self): return [] def __str__(self): return f"{self.lvalue} = new {self.contract_name}"
842
Python
.py
28
23.321429
65
0.627329
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,311
tmp_call.py
NioTheFirst_ScType/slither/slithir/tmp_operations/tmp_call.py
from slither.core.declarations import ( Event, Contract, SolidityVariableComposed, SolidityFunction, Structure, ) from slither.core.declarations.custom_error import CustomError from slither.core.variables.variable import Variable from slither.slithir.operations.lvalue import OperationWithLValue class TmpCall(OperationWithLValue): # pylint: disable=too-many-instance-attributes def __init__(self, called, nbr_arguments, result, type_call): assert isinstance( called, ( Contract, Variable, SolidityVariableComposed, SolidityFunction, Structure, Event, CustomError, ), ) super().__init__() self._called = called self._nbr_arguments = nbr_arguments self._type_call = type_call self._lvalue = result self._ori = None # self._callid = None self._gas = None self._value = None self._salt = None @property def call_value(self): return self._value @call_value.setter def call_value(self, v): self._value = v @property def call_gas(self): 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 call_id(self): return self._callid @call_id.setter def call_id(self, c): self._callid = c @property def read(self): return [self.called] @property def called(self): return self._called @called.setter def called(self, c): self._called = c @property def nbr_arguments(self): return self._nbr_arguments @property def type_call(self): return self._type_call @property def ori(self): return self._ori def set_ori(self, ori): self._ori = ori def __str__(self): return str(self.lvalue) + f" = TMPCALL{self.nbr_arguments} " + str(self._called)
2,204
Python
.py
80
19.875
88
0.595442
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,312
tmp_new_structure.py
NioTheFirst_ScType/slither/slithir/tmp_operations/tmp_new_structure.py
from slither.slithir.operations.lvalue import OperationWithLValue class TmpNewStructure(OperationWithLValue): def __init__(self, contract_name, lvalue): super().__init__() self._contract_name = contract_name self._lvalue = lvalue @property def contract_name(self): return self._contract_name @property def read(self): return [] def __str__(self): return f"{self.lvalue} = tmpnew {self.contract_name}"
478
Python
.py
14
27.642857
65
0.660131
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,313
argument.py
NioTheFirst_ScType/slither/slithir/tmp_operations/argument.py
from enum import Enum from slither.slithir.operations.operation import Operation class ArgumentType(Enum): CALL = 0 VALUE = 1 GAS = 2 DATA = 3 class Argument(Operation): def __init__(self, argument): super().__init__() self._argument = argument self._type = ArgumentType.CALL self._callid = None @property def argument(self): return self._argument @property def call_id(self): return self._callid @call_id.setter def call_id(self, c): self._callid = c @property def read(self): return [self.argument] def set_type(self, t): assert isinstance(t, ArgumentType) self._type = t def get_type(self): return self._type def __str__(self): call_id = "none" if self.call_id: call_id = f"(id ({self.call_id}))" return f"ARG_{self._type.name} {str(self._argument)} {call_id}"
963
Python
.py
35
20.828571
71
0.59542
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,314
solidity_call.py
NioTheFirst_ScType/slither/slithir/operations/solidity_call.py
from slither.core.declarations.solidity_variables import SolidityFunction from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue class SolidityCall(Call, OperationWithLValue): def __init__(self, function, nbr_arguments, result, type_call): assert isinstance(function, SolidityFunction) super().__init__() self._function = function self._nbr_arguments = nbr_arguments self._type_call = type_call self._lvalue = result @property def read(self): return self._unroll(self.arguments) @property def function(self): return self._function @property def nbr_arguments(self): return self._nbr_arguments @property def type_call(self): return self._type_call def __str__(self): if ( self.function == SolidityFunction("abi.decode()") and len(self.arguments) == 2 and isinstance(self.arguments[1], list) ): args = ( str(self.arguments[0]) + "(" + ",".join([str(a) for a in self.arguments[1]]) + ")" ) else: args = ",".join([str(a) for a in self.arguments]) lvalue = "" if self.lvalue: if isinstance(self.lvalue.type, (list,)): lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = " else: lvalue = f"{self.lvalue}({self.lvalue.type}) = " return lvalue + f"SOLIDITY_CALL {self.function.full_name}({args})"
1,590
Python
.py
41
29.97561
98
0.60026
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,315
internal_call.py
NioTheFirst_ScType/slither/slithir/operations/internal_call.py
from typing import Union, Tuple, List, Optional from slither.core.declarations import Modifier from slither.core.declarations.function import Function from slither.core.declarations.function_contract import FunctionContract from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue class InternalCall(Call, OperationWithLValue): # pylint: disable=too-many-instance-attributes def __init__( self, function: Union[Function, Tuple[str, str]], nbr_arguments, result, type_call ): super().__init__() self._contract_name = "" if isinstance(function, Function): self._function = function self._function_name = function.name if isinstance(function, FunctionContract): self._contract_name = function.contract_declarer.name else: self._function = None self._function_name, self._contract_name = function # self._contract = contract self._nbr_arguments = nbr_arguments self._type_call = type_call self._lvalue = result # function_candidates is only used as an helper to retrieve the "function" object # For top level function called through a import renamed # See SolidityImportPlaceHolder usages self.function_candidates: Optional[List[Function]] = None @property def read(self): return list(self._unroll(self.arguments)) @property def function(self): return self._function @function.setter def function(self, f): self._function = f @property def function_name(self): return self._function_name @property def contract_name(self): return self._contract_name @property def nbr_arguments(self): return self._nbr_arguments @property def type_call(self): return self._type_call @property def is_modifier_call(self): """ Check if the destination is a modifier :return: bool """ return isinstance(self.function, Modifier) def __str__(self): args = [str(a) for a in self.arguments] if not self.lvalue: lvalue = "" elif isinstance(self.lvalue.type, (list,)): lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = " else: lvalue = f"{self.lvalue}({self.lvalue.type}) = " if self.is_modifier_call: txt = "{}MODIFIER_CALL, {}({})" else: txt = "{}INTERNAL_CALL, {}({})" return txt.format(lvalue, self.function.canonical_name, ",".join(args))
2,675
Python
.py
69
30.826087
94
0.642004
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,316
high_level_call.py
NioTheFirst_ScType/slither/slithir/operations/high_level_call.py
from typing import Union from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue from slither.core.variables.variable import Variable from slither.core.declarations.solidity_variables import SolidityVariable from slither.core.declarations.function import Function from slither.slithir.utils.utils import is_valid_lvalue from slither.slithir.variables.constant import Constant class HighLevelCall(Call, OperationWithLValue): """ High level message call """ # pylint: disable=too-many-arguments,too-many-instance-attributes def __init__(self, destination, function_name, nbr_arguments, result, type_call): assert isinstance(function_name, Constant) assert is_valid_lvalue(result) or result is None self._check_destination(destination) super().__init__() self._destination = destination self._function_name = function_name self._nbr_arguments = nbr_arguments self._type_call = type_call self._lvalue = result self._callid = None # only used if gas/value != 0 self._function_instance = None self._call_value = None self._call_gas = None # Development function, to be removed once the code is stable # It is ovveride by LbraryCall def _check_destination(self, destination): # pylint: disable=no-self-use assert isinstance(destination, (Variable, SolidityVariable)) @property def call_id(self): return self._callid @call_id.setter def call_id(self, c): self._callid = c @property def call_value(self): return self._call_value @call_value.setter def call_value(self, v): self._call_value = v @property def call_gas(self): return self._call_gas @call_gas.setter def call_gas(self, v): self._call_gas = v @property def read(self): all_read = [self.destination, self.call_gas, self.call_value] + self._unroll(self.arguments) # remove None return [x for x in all_read if x] + [self.destination] @property def destination(self): return self._destination @property def function_name(self): return self._function_name @property def function(self) -> Union[Function, Variable]: return self._function_instance @function.setter def function(self, function): self._function_instance = function @property def nbr_arguments(self): return self._nbr_arguments @property def type_call(self): return self._type_call ################################################################################### ################################################################################### # region Analyses ################################################################################### ################################################################################### def is_static_call(self): # If solidity >0.5, STATICCALL is used if self.compilation_unit.solc_version and self.compilation_unit.solc_version >= "0.5.0": if isinstance(self.function, Function) and (self.function.view or self.function.pure): return True if isinstance(self.function, Variable): return True return False def can_reenter(self, callstack=None): """ Must be called after slithIR analysis pass For Solidity > 0.5, filter access to public variables and constant/pure/view For call to this. check if the destination can re-enter :param callstack: check for recursion :return: bool """ if self.is_static_call(): return False # If there is a call to itself # We can check that the function called is # reentrancy-safe if self.destination == SolidityVariable("this"): if isinstance(self.function, Variable): return False # In case of recursion, return False callstack = [] if callstack is None else callstack if self.function in callstack: return False callstack = callstack + [self.function] if self.function.can_reenter(callstack): return True if isinstance(self.destination, Variable): if not self.destination.is_reentrant: return False return True def can_send_eth(self): """ Must be called after slithIR analysis pass :return: bool """ return self._call_value is not None # endregion ################################################################################### ################################################################################### # region Built in ################################################################################### ################################################################################### def __str__(self): value = "" gas = "" if self.call_value: value = f"value:{self.call_value}" if self.call_gas: gas = f"gas:{self.call_gas}" arguments = [] if self.arguments: arguments = self.arguments txt = "{}HIGH_LEVEL_CALL, dest:{}({}), function:{}, arguments:{} {} {}" if not self.lvalue: lvalue = "" elif isinstance(self.lvalue.type, (list,)): lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = " else: lvalue = f"{self.lvalue}({self.lvalue.type}) = " return txt.format( lvalue, self.destination, self.destination.type, self.function_name, [str(x) for x in arguments], value, gas, )
5,965
Python
.py
150
31.44
100
0.550104
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,317
unary.py
NioTheFirst_ScType/slither/slithir/operations/unary.py
import logging from enum import Enum from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue from slither.slithir.exceptions import SlithIRError logger = logging.getLogger("BinaryOperationIR") class UnaryType(Enum): BANG = 0 # ! TILD = 1 # ~ @staticmethod def get_type(operation_type, isprefix): if isprefix: if operation_type == "!": return UnaryType.BANG if operation_type == "~": return UnaryType.TILD raise SlithIRError(f"get_type: Unknown operation type {operation_type}") def __str__(self): if self == UnaryType.BANG: return "!" if self == UnaryType.TILD: return "~" raise SlithIRError(f"str: Unknown operation type {self}") class Unary(OperationWithLValue): def __init__(self, result, variable, operation_type): assert is_valid_rvalue(variable) assert is_valid_lvalue(result) super().__init__() self._variable = variable self._type = operation_type self._lvalue = result @property def read(self): return [self._variable] @property def rvalue(self): return self._variable @property def type(self): return self._type @property def type_str(self): return str(self._type) def __str__(self): return f"{self.lvalue} = {self.type_str} {self.rvalue} "
1,518
Python
.py
45
26.466667
80
0.636052
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,318
member.py
NioTheFirst_ScType/slither/slithir/operations/member.py
from slither.core.declarations import Contract, Function from slither.core.declarations.custom_error import CustomError from slither.core.declarations.enum import Enum from slither.core.declarations.solidity_import_placeholder import SolidityImportPlaceHolder from slither.core.solidity_types import ElementaryType from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_rvalue from slither.slithir.variables.constant import Constant from slither.slithir.variables.reference import ReferenceVariable class Member(OperationWithLValue): def __init__(self, variable_left, variable_right, result): # Function can happen for something like # library FunctionExtensions { # function h(function() internal _t, uint8) internal { } # } # contract FunctionMembers { # using FunctionExtensions for function(); # # function f() public { # f.h(1); # } # } # Can be an ElementaryType because of bytes.concat, string.concat assert is_valid_rvalue(variable_left) or isinstance( variable_left, (Contract, Enum, Function, CustomError, SolidityImportPlaceHolder, ElementaryType), ) assert isinstance(variable_right, Constant) assert isinstance(result, ReferenceVariable) super().__init__() self._variable_left = variable_left self._variable_right = variable_right self._lvalue = result self._gas = None self._value = None @property def read(self): return [self.variable_left, self.variable_right] @property def variable_left(self): return self._variable_left @property def variable_right(self): return self._variable_right @property def call_value(self): return self._value @call_value.setter def call_value(self, v): self._value = v @property def call_gas(self): return self._gas @call_gas.setter def call_gas(self, gas): self._gas = gas def __str__(self): return f"{self.lvalue}({self.lvalue.type}) -> {self.variable_left}.{self.variable_right}"
2,252
Python
.py
58
31.982759
97
0.67934
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,319
operation.py
NioTheFirst_ScType/slither/slithir/operations/operation.py
import abc from slither.core.context.context import Context from slither.core.children.child_expression import ChildExpression from slither.core.children.child_node import ChildNode from slither.utils.utils import unroll class AbstractOperation(abc.ABC): @property @abc.abstractmethod def read(self): """ Return the list of variables READ """ pass # pylint: disable=unnecessary-pass @property @abc.abstractmethod def used(self): """ Return the list of variables used """ pass # pylint: disable=unnecessary-pass class Operation(Context, ChildExpression, ChildNode, AbstractOperation): @property def used(self): """ By default used is all the variables read """ return self.read # if array inside the parameters @staticmethod def _unroll(l): return unroll(l)
913
Python
.py
31
23.483871
72
0.684932
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,320
phi_callback.py
NioTheFirst_ScType/slither/slithir/operations/phi_callback.py
from slither.slithir.utils.utils import is_valid_lvalue from slither.slithir.operations.phi import Phi class PhiCallback(Phi): def __init__(self, left_variable, nodes, call_ir, rvalue): assert is_valid_lvalue(left_variable) assert isinstance(nodes, set) super().__init__(left_variable, nodes) self._call_ir = call_ir self._rvalues = [rvalue] self._rvalue_no_callback = rvalue @property def callee_ir(self): return self._call_ir @property def read(self): return self.rvalues @property def rvalues(self): return self._rvalues @property def rvalue_no_callback(self): """ rvalue if callback are not considered """ return self._rvalue_no_callback @rvalues.setter def rvalues(self, vals): self._rvalues = vals @property def nodes(self): return self._nodes def __str__(self): return f"{self.lvalue}({self.lvalue.type}) := \u03D5({[v.ssa_name for v in self._rvalues]})"
1,055
Python
.py
33
25.121212
100
0.632774
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,321
library_call.py
NioTheFirst_ScType/slither/slithir/operations/library_call.py
from slither.core.declarations import Function from slither.slithir.operations.high_level_call import HighLevelCall from slither.core.declarations.contract import Contract class LibraryCall(HighLevelCall): """ High level message call """ # Development function, to be removed once the code is stable def _check_destination(self, destination): assert isinstance(destination, Contract) def can_reenter(self, callstack=None): """ Must be called after slithIR analysis pass :return: bool """ if self.is_static_call(): return False # In case of recursion, return False callstack = [] if callstack is None else callstack if self.function in callstack: return False callstack = callstack + [self.function] return self.function.can_reenter(callstack) def __str__(self): gas = "" if self.call_gas: gas = f"gas:{self.call_gas}" arguments = [] if self.arguments: arguments = self.arguments if not self.lvalue: lvalue = "" elif isinstance(self.lvalue.type, (list,)): lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = " else: lvalue = f"{self.lvalue}({self.lvalue.type}) = " txt = "{}LIBRARY_CALL, dest:{}, function:{}, arguments:{} {}" function_name = self.function_name if self.function: if isinstance(self.function, Function): function_name = self.function.canonical_name return txt.format( lvalue, self.destination, function_name, [str(x) for x in arguments], gas, )
1,771
Python
.py
48
27.770833
86
0.600466
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,322
phi.py
NioTheFirst_ScType/slither/slithir/operations/phi.py
from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue class Phi(OperationWithLValue): def __init__(self, left_variable, nodes): # When Phi operations are created the # correct indexes of the variables are not yet computed # We store the nodes where the variables are written # so we can update the rvalues of the Phi operation # after its instantiation assert is_valid_lvalue(left_variable) assert isinstance(nodes, set) super().__init__() self._lvalue = left_variable self._rvalues = [] self._nodes = nodes @property def read(self): return self.rvalues @property def rvalues(self): return self._rvalues @rvalues.setter def rvalues(self, vals): self._rvalues = vals @property def nodes(self): return self._nodes def __str__(self): return f"{self.lvalue}({self.lvalue.type}) := \u03D5({[str(v) for v in self._rvalues]})"
1,063
Python
.py
29
29.62069
96
0.655307
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,323
transfer.py
NioTheFirst_ScType/slither/slithir/operations/transfer.py
from slither.slithir.operations.call import Call from slither.core.variables.variable import Variable from slither.core.declarations.solidity_variables import SolidityVariable class Transfer(Call): def __init__(self, destination, value): assert isinstance(destination, (Variable, SolidityVariable)) self._destination = destination super().__init__() self._call_value = value def can_send_eth(self): return True @property def call_value(self): return self._call_value @property def read(self): return [self.destination, self.call_value] @property def destination(self): return self._destination def __str__(self): value = f"value:{self.call_value}" return f"Transfer dest:{self.destination} {value}"
823
Python
.py
23
29.391304
73
0.688131
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,324
nop.py
NioTheFirst_ScType/slither/slithir/operations/nop.py
from .operation import Operation class Nop(Operation): @property def read(self): return [] @property def used(self): return [] def __str__(self): return "NOP"
207
Python
.py
10
14.9
32
0.590674
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,325
event_call.py
NioTheFirst_ScType/slither/slithir/operations/event_call.py
from slither.slithir.operations.call import Call class EventCall(Call): def __init__(self, name): super().__init__() self._name = name # todo add instance of the Event @property def name(self): return self._name @property def read(self): return self._unroll(self.arguments) def __str__(self): args = [str(a) for a in self.arguments] return f"Emit {self.name}({','.join(args)})"
463
Python
.py
15
24.2
52
0.600451
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,326
condition.py
NioTheFirst_ScType/slither/slithir/operations/condition.py
from slither.slithir.operations.operation import Operation from slither.slithir.utils.utils import is_valid_rvalue class Condition(Operation): """ Condition Only present as last operation in conditional node """ def __init__(self, value): assert is_valid_rvalue(value) super().__init__() self._value = value @property def read(self): return [self.value] @property def value(self): return self._value def __str__(self): return f"CONDITION {self.value}"
547
Python
.py
19
22.789474
58
0.654511
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,327
init_array.py
NioTheFirst_ScType/slither/slithir/operations/init_array.py
from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_rvalue class InitArray(OperationWithLValue): def __init__(self, init_values, lvalue): # init_values can be an array of n dimension # reduce was removed in py3 super().__init__() def reduce(xs): result = True for i in xs: result = result and i return result def check(elem): if isinstance(elem, (list,)): return reduce(elem) return is_valid_rvalue(elem) assert check(init_values) self._init_values = init_values self._lvalue = lvalue @property def read(self): return self._unroll(self.init_values) @property def init_values(self): return list(self._init_values) def __str__(self): def convert(elem): if isinstance(elem, (list,)): return str([convert(x) for x in elem]) return str(elem) init_values = convert(self.init_values) return f"{self.lvalue}({self.lvalue.type}) = {init_values}"
1,170
Python
.py
32
27.15625
68
0.596103
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,328
type_conversion.py
NioTheFirst_ScType/slither/slithir/operations/type_conversion.py
from slither.core.declarations import Contract from slither.core.solidity_types.type import Type from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue class TypeConversion(OperationWithLValue): def __init__(self, result, variable, variable_type): super().__init__() assert is_valid_rvalue(variable) or isinstance(variable, Contract) assert is_valid_lvalue(result) assert isinstance(variable_type, Type) self._variable = variable self._type = variable_type self._lvalue = result @property def variable(self): return self._variable @property def type(self): return self._type @property def read(self): return [self.variable] def __str__(self): return str(self.lvalue) + f" = CONVERT {self.variable} to {self.type}"
925
Python
.py
24
32.25
78
0.697987
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,329
delete.py
NioTheFirst_ScType/slither/slithir/operations/delete.py
from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue class Delete(OperationWithLValue): """ Delete has a lvalue, as it has for effect to change the value of its operand """ def __init__(self, lvalue, variable): assert is_valid_lvalue(variable) super().__init__() self._variable = variable self._lvalue = lvalue @property def read(self): return [self.variable] @property def variable(self): return self._variable def __str__(self): return f"{self.lvalue} = delete {self.variable} "
653
Python
.py
20
26.5
65
0.664537
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,330
codesize.py
NioTheFirst_ScType/slither/slithir/operations/codesize.py
from slither.core.solidity_types import ElementaryType from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue class CodeSize(OperationWithLValue): def __init__(self, value, lvalue): super().__init__() assert is_valid_rvalue(value) assert is_valid_lvalue(lvalue) self._value = value self._lvalue = lvalue lvalue.set_type(ElementaryType("uint256")) @property def read(self): return [self._value] @property def value(self): return self._value def __str__(self): return f"{self.lvalue} -> CODESIZE {self.value}"
693
Python
.py
19
30.157895
72
0.681614
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,331
return_operation.py
NioTheFirst_ScType/slither/slithir/operations/return_operation.py
from slither.core.declarations import Function from slither.slithir.operations.operation import Operation from slither.slithir.variables.tuple import TupleVariable from slither.slithir.utils.utils import is_valid_rvalue class Return(Operation): """ Return Only present as last operation in RETURN node """ def __init__(self, values): # Note: Can return None # ex: return call() # where call() dont return if not isinstance(values, list): assert ( is_valid_rvalue(values) or isinstance(values, (TupleVariable, Function)) or values is None ) if values is None: values = [] else: values = [values] else: # Remove None # Prior Solidity 0.5 # return (0,) # was valid for returns(uint) values = [v for v in values if not v is None] self._valid_value(values) super().__init__() self._values = values def _valid_value(self, value): if isinstance(value, list): assert all(self._valid_value(v) for v in value) else: assert is_valid_rvalue(value) or isinstance(value, (TupleVariable, Function)) return True @property def read(self): return self._unroll(self.values) @property def values(self): return self._unroll(self._values) def __str__(self): return f"RETURN {','.join([f'{x}' for x in self.values])}"
1,575
Python
.py
46
24.978261
89
0.581197
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,332
__init__.py
NioTheFirst_ScType/slither/slithir/operations/__init__.py
from .assignment import Assignment from .binary import Binary, BinaryType from .call import Call from .condition import Condition from .delete import Delete from .event_call import EventCall from .high_level_call import HighLevelCall from .index import Index from .init_array import InitArray from .internal_call import InternalCall from .internal_dynamic_call import InternalDynamicCall from .library_call import LibraryCall from .low_level_call import LowLevelCall from .lvalue import OperationWithLValue from .member import Member from .new_array import NewArray from .new_elementary_type import NewElementaryType from .new_contract import NewContract from .new_structure import NewStructure from .operation import Operation from .return_operation import Return from .send import Send from .solidity_call import SolidityCall from .transfer import Transfer from .type_conversion import TypeConversion from .unary import Unary, UnaryType from .unpack import Unpack from .length import Length from .phi import Phi from .phi_callback import PhiCallback from .nop import Nop
1,073
Python
.py
31
33.612903
54
0.858925
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,333
send.py
NioTheFirst_ScType/slither/slithir/operations/send.py
from slither.core.declarations.solidity_variables import SolidityVariable from slither.core.variables.variable import Variable from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue class Send(Call, OperationWithLValue): def __init__(self, destination, value, result): assert is_valid_lvalue(result) assert isinstance(destination, (Variable, SolidityVariable)) super().__init__() self._destination = destination self._lvalue = result self._call_value = value def can_send_eth(self): return True @property def call_value(self): return self._call_value @property def read(self): return [self.destination, self.call_value] @property def destination(self): return self._destination def __str__(self): value = f"value:{self.call_value}" return str(self.lvalue) + f" = SEND dest:{self.destination} {value}" #
1,061
Python
.py
28
31.821429
76
0.705767
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,334
length.py
NioTheFirst_ScType/slither/slithir/operations/length.py
from slither.core.solidity_types import ElementaryType from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue class Length(OperationWithLValue): def __init__(self, value, lvalue): super().__init__() assert is_valid_rvalue(value) assert is_valid_lvalue(lvalue) self._value = value self._lvalue = lvalue lvalue.set_type(ElementaryType("uint256")) @property def read(self): return [self._value] @property def value(self): return self._value def __str__(self): return f"{self.lvalue} -> LENGTH {self.value}"
689
Python
.py
19
29.947368
72
0.679699
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,335
new_structure.py
NioTheFirst_ScType/slither/slithir/operations/new_structure.py
from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue from slither.core.declarations.structure import Structure class NewStructure(Call, OperationWithLValue): def __init__(self, structure, lvalue): super().__init__() assert isinstance(structure, Structure) assert is_valid_lvalue(lvalue) self._structure = structure # todo create analyze to add the contract instance self._lvalue = lvalue @property def read(self): return self._unroll(self.arguments) @property def structure(self): return self._structure @property def structure_name(self): return self.structure.name def __str__(self): args = [str(a) for a in self.arguments] return f"{self.lvalue} = new {self.structure_name}({','.join(args)})"
942
Python
.py
24
32.916667
77
0.698901
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,336
new_array.py
NioTheFirst_ScType/slither/slithir/operations/new_array.py
from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.operations.call import Call from slither.core.solidity_types.type import Type class NewArray(Call, OperationWithLValue): def __init__(self, depth, array_type, lvalue): super().__init__() assert isinstance(array_type, Type) self._depth = depth self._array_type = array_type self._lvalue = lvalue @property def array_type(self): return self._array_type @property def read(self): return self._unroll(self.arguments) @property def depth(self): return self._depth def __str__(self): args = [str(a) for a in self.arguments] return f"{self.lvalue} = new {self.array_type}{'[]' * self.depth}({','.join(args)})"
809
Python
.py
22
30.363636
92
0.657692
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,337
index.py
NioTheFirst_ScType/slither/slithir/operations/index.py
from slither.core.declarations import SolidityVariableComposed from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue from slither.slithir.variables.reference import ReferenceVariable class Index(OperationWithLValue): def __init__(self, result, left_variable, right_variable, index_type): super().__init__() assert is_valid_lvalue(left_variable) or left_variable == SolidityVariableComposed( "msg.data" ) assert is_valid_rvalue(right_variable) assert isinstance(result, ReferenceVariable) self._variables = [left_variable, right_variable] self._type = index_type self._lvalue = result @property def read(self): return list(self.variables) @property def variables(self): return self._variables @property def variable_left(self): return self._variables[0] @property def variable_right(self): return self._variables[1] @property def index_type(self): return self._type def __str__(self): return f"{self.lvalue}({self.lvalue.type}) -> {self.variable_left}[{self.variable_right}]"
1,240
Python
.py
32
32.125
98
0.695
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,338
assignment.py
NioTheFirst_ScType/slither/slithir/operations/assignment.py
import logging from slither.core.declarations.function import Function from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue from slither.slithir.variables import TupleVariable, ReferenceVariable logger = logging.getLogger("AssignmentOperationIR") class Assignment(OperationWithLValue): def __init__(self, left_variable, right_variable, variable_return_type): assert is_valid_lvalue(left_variable) assert is_valid_rvalue(right_variable) or isinstance( right_variable, (Function, TupleVariable) ) super().__init__() self._variables = [left_variable, right_variable] self._lvalue = left_variable self._rvalue = right_variable self._variable_return_type = variable_return_type @property def variables(self): return list(self._variables) @property def read(self): return [self.rvalue] @property def variable_return_type(self): return self._variable_return_type @property def rvalue(self): return self._rvalue def __str__(self): if isinstance(self.lvalue, ReferenceVariable): points = self.lvalue.points_to while isinstance(points, ReferenceVariable): points = points.points_to return f"{self.lvalue} (->{points}) := {self.rvalue}({self.rvalue.type})" return f"{self.lvalue}({self.lvalue.type}) := {self.rvalue}({self.rvalue.type})"
1,538
Python
.py
36
35.472222
88
0.689216
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,339
new_contract.py
NioTheFirst_ScType/slither/slithir/operations/new_contract.py
from slither.slithir.operations import Call, OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue from slither.slithir.variables.constant import Constant class NewContract(Call, OperationWithLValue): # pylint: disable=too-many-instance-attributes def __init__(self, contract_name, lvalue): assert isinstance(contract_name, Constant) assert is_valid_lvalue(lvalue) super().__init__() self._contract_name = contract_name # todo create analyze to add the contract instance self._lvalue = lvalue self._callid = None # only used if gas/value != 0 self._call_value = None self._call_salt = None @property def call_value(self): return self._call_value @call_value.setter def call_value(self, v): self._call_value = v @property def call_id(self): return self._callid @call_id.setter def call_id(self, c): self._callid = c @property def call_salt(self): return self._call_salt @call_salt.setter def call_salt(self, s): self._call_salt = s @property def contract_name(self): return self._contract_name @property def read(self): return self._unroll(self.arguments) @property def contract_created(self): contract_name = self.contract_name contract_instance = self.node.file_scope.get_contract_from_name(contract_name) return contract_instance ################################################################################### ################################################################################### # region Analyses ################################################################################### ################################################################################### def can_reenter(self, callstack=None): """ Must be called after slithIR analysis pass For Solidity > 0.5, filter access to public variables and constant/pure/view For call to this. check if the destination can re-enter :param callstack: check for recursion :return: bool """ callstack = [] if callstack is None else callstack constructor = self.contract_created.constructor if constructor is None: return False if constructor in callstack: return False callstack = callstack + [constructor] return constructor.can_reenter(callstack) def can_send_eth(self): """ Must be called after slithIR analysis pass :return: bool """ return self._call_value is not None # endregion def __str__(self): options = "" if self.call_value: options = f"value:{self.call_value} " if self.call_salt: options += f"salt:{self.call_salt} " args = [str(a) for a in self.arguments] return f"{self.lvalue} = new {self.contract_name}({','.join(args)}) {options}"
3,065
Python
.py
79
31.21519
93
0.564983
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,340
internal_dynamic_call.py
NioTheFirst_ScType/slither/slithir/operations/internal_dynamic_call.py
from slither.core.solidity_types import FunctionType from slither.core.variables.variable import Variable from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue class InternalDynamicCall( Call, OperationWithLValue ): # pylint: disable=too-many-instance-attributes def __init__(self, lvalue, function, function_type): assert isinstance(function_type, FunctionType) assert isinstance(function, Variable) assert is_valid_lvalue(lvalue) or lvalue is None super().__init__() self._function = function self._function_type = function_type self._lvalue = lvalue self._callid = None # only used if gas/value != 0 self._call_value = None self._call_gas = None @property def read(self): return self._unroll(self.arguments) + [self.function] @property def function(self): return self._function @property def function_type(self): return self._function_type @property def call_value(self): return self._call_value @call_value.setter def call_value(self, v): self._call_value = v @property def call_gas(self): return self._call_gas @call_gas.setter def call_gas(self, v): self._call_gas = v @property def call_id(self): return self._callid @call_id.setter def call_id(self, c): self._callid = c def __str__(self): value = "" gas = "" args = [str(a) for a in self.arguments] if self.call_value: value = f"value:{self.call_value}" if self.call_gas: gas = f"gas:{self.call_gas}" if not self.lvalue: lvalue = "" elif isinstance(self.lvalue.type, (list,)): lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = " else: lvalue = f"{self.lvalue}({self.lvalue.type}) = " txt = "{}INTERNAL_DYNAMIC_CALL {}({}) {} {}" return txt.format(lvalue, self.function.name, ",".join(args), value, gas)
2,193
Python
.py
62
28.096774
86
0.626062
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,341
new_elementary_type.py
NioTheFirst_ScType/slither/slithir/operations/new_elementary_type.py
from slither.core.solidity_types.elementary_type import ElementaryType from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue class NewElementaryType(Call, OperationWithLValue): def __init__(self, new_type, lvalue): assert isinstance(new_type, ElementaryType) assert is_valid_lvalue(lvalue) super().__init__() self._type = new_type self._lvalue = lvalue @property def type(self): return self._type @property def read(self): return list(self.arguments) def __str__(self): args = [str(a) for a in self.arguments] return f"{self.lvalue} = new {self._type}({','.join(args)})"
790
Python
.py
20
33.4
70
0.692408
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,342
low_level_call.py
NioTheFirst_ScType/slither/slithir/operations/low_level_call.py
from slither.slithir.operations.call import Call from slither.slithir.operations.lvalue import OperationWithLValue from slither.core.variables.variable import Variable from slither.core.declarations.solidity_variables import SolidityVariable from slither.slithir.variables.constant import Constant class LowLevelCall(Call, OperationWithLValue): # pylint: disable=too-many-instance-attributes """ High level message call """ def __init__(self, destination, function_name, nbr_arguments, result, type_call): # pylint: disable=too-many-arguments assert isinstance(destination, (Variable, SolidityVariable)) assert isinstance(function_name, Constant) super().__init__() self._destination = destination self._function_name = function_name self._nbr_arguments = nbr_arguments self._type_call = type_call self._lvalue = result self._callid = None # only used if gas/value != 0 self._call_value = None self._call_gas = None @property def call_id(self): return self._callid @call_id.setter def call_id(self, c): self._callid = c @property def call_value(self): return self._call_value @call_value.setter def call_value(self, v): self._call_value = v @property def call_gas(self): return self._call_gas @call_gas.setter def call_gas(self, v): self._call_gas = v @property def read(self): all_read = [self.destination, self.call_gas, self.call_value] + self.arguments # remove None return self._unroll([x for x in all_read if x]) def can_reenter(self, _callstack=None): """ Must be called after slithIR analysis pass :return: bool """ if self.function_name == "staticcall": return False return True def can_send_eth(self): """ Must be called after slithIR analysis pass :return: bool """ return self._call_value is not None @property def destination(self): return self._destination @property def function_name(self): return self._function_name @property def nbr_arguments(self): return self._nbr_arguments @property def type_call(self): return self._type_call def __str__(self): value = "" gas = "" if self.call_value: value = f"value:{self.call_value}" if self.call_gas: gas = f"gas:{self.call_gas}" arguments = [] if self.arguments: arguments = self.arguments return_type = self.lvalue.type if return_type and isinstance(return_type, list): return_type = ",".join(str(x) for x in return_type) txt = "{}({}) = LOW_LEVEL_CALL, dest:{}, function:{}, arguments:{} {} {}" return txt.format( self.lvalue, return_type, self.destination, self.function_name, [str(x) for x in arguments], value, gas, )
3,143
Python
.py
94
25.446809
94
0.611955
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,343
call.py
NioTheFirst_ScType/slither/slithir/operations/call.py
from typing import Optional, List from slither.slithir.operations.operation import Operation class Call(Operation): def __init__(self) -> None: super().__init__() self._arguments = [] @property def arguments(self): return self._arguments @arguments.setter def arguments(self, v): self._arguments = v def can_reenter(self, _callstack: Optional[List] = None) -> bool: # pylint: disable=no-self-use """ Must be called after slithIR analysis pass :return: bool """ return False def can_send_eth(self) -> bool: # pylint: disable=no-self-use """ Must be called after slithIR analysis pass :return: bool """ return False
763
Python
.py
24
24.666667
100
0.613388
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,344
lvalue.py
NioTheFirst_ScType/slither/slithir/operations/lvalue.py
from slither.slithir.operations.operation import Operation class OperationWithLValue(Operation): """ Operation with a lvalue """ def __init__(self): super().__init__() self._lvalue = None @property def lvalue(self): return self._lvalue @property def used(self): return self.read + [self.lvalue] @lvalue.setter def lvalue(self, lvalue): self._lvalue = lvalue
445
Python
.py
17
20.058824
58
0.631829
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,345
binary.py
NioTheFirst_ScType/slither/slithir/operations/binary.py
import logging from enum import Enum from slither.core.declarations import Function from slither.core.solidity_types import ElementaryType from slither.slithir.exceptions import SlithIRError from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue from slither.slithir.variables import ReferenceVariable logger = logging.getLogger("BinaryOperationIR") class BinaryType(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 # || @staticmethod def return_bool(operation_type): return operation_type in [ BinaryType.OROR, BinaryType.ANDAND, BinaryType.LESS, BinaryType.GREATER, BinaryType.LESS_EQUAL, BinaryType.GREATER_EQUAL, BinaryType.EQUAL, BinaryType.NOT_EQUAL, ] @staticmethod def get_type(operation_type): # pylint: disable=too-many-branches if operation_type == "**": return BinaryType.POWER if operation_type == "*": return BinaryType.MULTIPLICATION if operation_type == "/": return BinaryType.DIVISION if operation_type == "%": return BinaryType.MODULO if operation_type == "+": return BinaryType.ADDITION if operation_type == "-": return BinaryType.SUBTRACTION if operation_type == "<<": return BinaryType.LEFT_SHIFT if operation_type == ">>": return BinaryType.RIGHT_SHIFT if operation_type == "&": return BinaryType.AND if operation_type == "^": return BinaryType.CARET if operation_type == "|": return BinaryType.OR if operation_type == "<": return BinaryType.LESS if operation_type == ">": return BinaryType.GREATER if operation_type == "<=": return BinaryType.LESS_EQUAL if operation_type == ">=": return BinaryType.GREATER_EQUAL if operation_type == "==": return BinaryType.EQUAL if operation_type == "!=": return BinaryType.NOT_EQUAL if operation_type == "&&": return BinaryType.ANDAND if operation_type == "||": return BinaryType.OROR raise SlithIRError(f"get_type: Unknown operation type {operation_type})") def can_be_checked_for_overflow(self): return self in [ BinaryType.POWER, BinaryType.MULTIPLICATION, BinaryType.MODULO, BinaryType.ADDITION, BinaryType.SUBTRACTION, BinaryType.DIVISION, ] def __str__(self): # pylint: disable=too-many-branches if self == BinaryType.POWER: return "**" if self == BinaryType.MULTIPLICATION: return "*" if self == BinaryType.DIVISION: return "/" if self == BinaryType.MODULO: return "%" if self == BinaryType.ADDITION: return "+" if self == BinaryType.SUBTRACTION: return "-" if self == BinaryType.LEFT_SHIFT: return "<<" if self == BinaryType.RIGHT_SHIFT: return ">>" if self == BinaryType.AND: return "&" if self == BinaryType.CARET: return "^" if self == BinaryType.OR: return "|" if self == BinaryType.LESS: return "<" if self == BinaryType.GREATER: return ">" if self == BinaryType.LESS_EQUAL: return "<=" if self == BinaryType.GREATER_EQUAL: return ">=" if self == BinaryType.EQUAL: return "==" if self == BinaryType.NOT_EQUAL: return "!=" if self == BinaryType.ANDAND: return "&&" if self == BinaryType.OROR: return "||" raise SlithIRError(f"str: Unknown operation type {self} {type(self)})") class Binary(OperationWithLValue): def __init__(self, result, left_variable, right_variable, operation_type: BinaryType): assert is_valid_rvalue(left_variable) or isinstance(left_variable, Function) assert is_valid_rvalue(right_variable) or isinstance(right_variable, Function) assert is_valid_lvalue(result) assert isinstance(operation_type, BinaryType) super().__init__() self._variables = [left_variable, right_variable] self._type = operation_type self._lvalue = result if BinaryType.return_bool(operation_type): result.set_type(ElementaryType("bool")) else: result.set_type(left_variable.type) @property def read(self): return [self.variable_left, self.variable_right] @property def get_variable(self): return self._variables @property def variable_left(self): return self._variables[0] @property def variable_right(self): return self._variables[1] @property def type(self): return self._type @property def type_str(self): if self.node.scope.is_checked and self._type.can_be_checked_for_overflow(): return "(c)" + str(self._type) return str(self._type) def __str__(self): if isinstance(self.lvalue, ReferenceVariable): points = self.lvalue.points_to while isinstance(points, ReferenceVariable): points = points.points_to return f"{str(self.lvalue)}(-> {points}) = {self.variable_left} {self.type_str} {self.variable_right}" return f"{str(self.lvalue)}({self.lvalue.type}) = {self.variable_left} {self.type_str} {self.variable_right}"
6,166
Python
.py
172
26.761628
117
0.584268
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,346
unpack.py
NioTheFirst_ScType/slither/slithir/operations/unpack.py
from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.utils.utils import is_valid_lvalue from slither.slithir.variables.tuple import TupleVariable class Unpack(OperationWithLValue): def __init__(self, result, tuple_var, idx): assert is_valid_lvalue(result) assert isinstance(tuple_var, TupleVariable) assert isinstance(idx, int) super().__init__() self._tuple = tuple_var self._idx = idx self._lvalue = result @property def read(self): return [self.tuple] @property def tuple(self): return self._tuple @property def index(self): return self._idx def __str__(self): return f"{self.lvalue}({self.lvalue.type})= UNPACK {self.tuple} index: {self.index} "
810
Python
.py
23
28.73913
93
0.669654
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,347
ssa.py
NioTheFirst_ScType/slither/slithir/utils/ssa.py
import logging from slither.core.cfg.node import NodeType from slither.core.declarations import ( Contract, Enum, Function, SolidityFunction, SolidityVariable, Structure, ) from slither.core.declarations.solidity_import_placeholder import SolidityImportPlaceHolder from slither.core.solidity_types.type import Type from slither.core.variables.local_variable import LocalVariable from slither.core.variables.state_variable import StateVariable from slither.core.variables.top_level_variable import TopLevelVariable from slither.slithir.operations import ( Assignment, Binary, Condition, Delete, EventCall, HighLevelCall, Index, InitArray, InternalCall, InternalDynamicCall, Length, LibraryCall, LowLevelCall, Member, NewArray, NewContract, NewElementaryType, NewStructure, OperationWithLValue, Phi, PhiCallback, Return, Send, SolidityCall, Transfer, TypeConversion, Unary, Unpack, Nop, ) from slither.slithir.operations.codesize import CodeSize from slither.slithir.variables import ( Constant, LocalIRVariable, ReferenceVariable, ReferenceVariableSSA, StateIRVariable, TemporaryVariable, TemporaryVariableSSA, TupleVariable, TupleVariableSSA, ) from slither.slithir.exceptions import SlithIRError logger = logging.getLogger("SSA_Conversion") ################################################################################### ################################################################################### # region SlihtIR variables to SSA ################################################################################### ################################################################################### def transform_slithir_vars_to_ssa(function): """ Transform slithIR vars to SSA (TemporaryVariable, ReferenceVariable, TupleVariable) """ variables = [] for node in function.nodes: for ir in node.irs_ssa: if isinstance(ir, OperationWithLValue) and not ir.lvalue in variables: variables += [ir.lvalue] tmp_variables = [v for v in variables if isinstance(v, TemporaryVariable)] for idx, _ in enumerate(tmp_variables): tmp_variables[idx].index = idx ref_variables = [v for v in variables if isinstance(v, ReferenceVariable)] for idx, _ in enumerate(ref_variables): ref_variables[idx].index = idx tuple_variables = [v for v in variables if isinstance(v, TupleVariable)] for idx, _ in enumerate(tuple_variables): tuple_variables[idx].index = idx ################################################################################### ################################################################################### # region SSA conversion ################################################################################### ################################################################################### # pylint: disable=too-many-arguments,too-many-locals,too-many-nested-blocks,too-many-statements,too-many-branches def add_ssa_ir(function, all_state_variables_instances): """ Add SSA version of the IR Args: function all_state_variables_instances """ if not function.is_implemented: return init_definition = {} for v in function.parameters: if v.name: init_definition[v.name] = (v, function.entry_point) function.entry_point.add_ssa_ir(Phi(LocalIRVariable(v), set())) for v in function.returns: if v.name: init_definition[v.name] = (v, function.entry_point) # We only add phi function for state variable at entry node if # The state variable is used # And if the state variables is written in another function (otherwise its stay at index 0) for (_, variable_instance) in all_state_variables_instances.items(): if is_used_later(function.entry_point, variable_instance): # rvalues are fixed in solc_parsing.declaration.function function.entry_point.add_ssa_ir(Phi(StateIRVariable(variable_instance), set())) add_phi_origins(function.entry_point, init_definition, {}) for node in function.nodes: for (variable, nodes) in node.phi_origins_local_variables.values(): if len(nodes) < 2: continue if not is_used_later(node, variable): continue node.add_ssa_ir(Phi(LocalIRVariable(variable), nodes)) for (variable, nodes) in node.phi_origins_state_variables.values(): if len(nodes) < 2: continue # if not is_used_later(node, variable.name, []): # continue node.add_ssa_ir(Phi(StateIRVariable(variable), nodes)) init_local_variables_instances = {} for v in function.parameters: if v.name: new_var = LocalIRVariable(v) function.add_parameter_ssa(new_var) if new_var.is_storage: fake_variable = LocalIRVariable(v) fake_variable.name = "STORAGE_" + fake_variable.name fake_variable.set_location("reference_to_storage") new_var.refers_to = {fake_variable} init_local_variables_instances[fake_variable.name] = fake_variable init_local_variables_instances[v.name] = new_var for v in function.returns: if v.name: new_var = LocalIRVariable(v) function.add_return_ssa(new_var) if new_var.is_storage: fake_variable = LocalIRVariable(v) fake_variable.name = "STORAGE_" + fake_variable.name fake_variable.set_location("reference_to_storage") new_var.refers_to = {fake_variable} init_local_variables_instances[fake_variable.name] = fake_variable init_local_variables_instances[v.name] = new_var all_init_local_variables_instances = dict(init_local_variables_instances) init_state_variables_instances = dict(all_state_variables_instances) initiate_all_local_variables_instances( function.nodes, init_local_variables_instances, all_init_local_variables_instances, ) generate_ssa_irs( function.entry_point, dict(init_local_variables_instances), all_init_local_variables_instances, dict(init_state_variables_instances), all_state_variables_instances, init_local_variables_instances, [], ) fix_phi_rvalues_and_storage_ref( function.entry_point, dict(init_local_variables_instances), all_init_local_variables_instances, dict(init_state_variables_instances), all_state_variables_instances, init_local_variables_instances, ) def generate_ssa_irs( node, local_variables_instances, all_local_variables_instances, state_variables_instances, all_state_variables_instances, init_local_variables_instances, visited, ): if node in visited: return if node.type in [NodeType.ENDIF, NodeType.ENDLOOP] and any( not father in visited for father in node.fathers ): return # visited is shared visited.append(node) for ir in node.irs_ssa: assert isinstance(ir, Phi) update_lvalue( ir, node, local_variables_instances, all_local_variables_instances, state_variables_instances, all_state_variables_instances, ) # these variables are lived only during the liveness of the block # They dont need phi function temporary_variables_instances = {} reference_variables_instances = {} tuple_variables_instances = {} for ir in node.irs: new_ir = copy_ir( ir, local_variables_instances, state_variables_instances, temporary_variables_instances, reference_variables_instances, tuple_variables_instances, all_local_variables_instances, ) new_ir.set_expression(ir.expression) new_ir.set_node(ir.node) update_lvalue( new_ir, node, local_variables_instances, all_local_variables_instances, state_variables_instances, all_state_variables_instances, ) if new_ir: node.add_ssa_ir(new_ir) if isinstance(ir, (InternalCall, HighLevelCall, InternalDynamicCall, LowLevelCall)): if isinstance(ir, LibraryCall): continue for variable in all_state_variables_instances.values(): if not is_used_later(node, variable): continue new_var = StateIRVariable(variable) new_var.index = all_state_variables_instances[variable.canonical_name].index + 1 all_state_variables_instances[variable.canonical_name] = new_var state_variables_instances[variable.canonical_name] = new_var phi_ir = PhiCallback(new_var, {node}, new_ir, variable) # rvalues are fixed in solc_parsing.declaration.function node.add_ssa_ir(phi_ir) if isinstance(new_ir, (Assignment, Binary)): if isinstance(new_ir.lvalue, LocalIRVariable): if new_ir.lvalue.is_storage: if isinstance(new_ir.rvalue, ReferenceVariable): refers_to = new_ir.rvalue.points_to_origin new_ir.lvalue.add_refers_to(refers_to) # Discard Constant # This can happen on yul, like # assembly { var.slot = some_value } # Here we do not keep track of the references as we do not track # such low level manipulation # However we could extend our storage model to do so in the future elif not isinstance(new_ir.rvalue, Constant): new_ir.lvalue.add_refers_to(new_ir.rvalue) for succ in node.dominator_successors: generate_ssa_irs( succ, dict(local_variables_instances), all_local_variables_instances, dict(state_variables_instances), all_state_variables_instances, init_local_variables_instances, visited, ) for dominated in node.dominance_frontier: generate_ssa_irs( dominated, dict(local_variables_instances), all_local_variables_instances, dict(state_variables_instances), all_state_variables_instances, init_local_variables_instances, visited, ) # endregion ################################################################################### ################################################################################### # region Helpers ################################################################################### ################################################################################### def last_name(n, var, init_vars): candidates = [] # Todo optimize by creating a variables_ssa_written attribute for ir_ssa in n.irs_ssa: if isinstance(ir_ssa, OperationWithLValue): lvalue = ir_ssa.lvalue while isinstance(lvalue, ReferenceVariable): lvalue = lvalue.points_to if lvalue and lvalue.name == var.name: candidates.append(lvalue) if n.variable_declaration and n.variable_declaration.name == var.name: candidates.append(LocalIRVariable(n.variable_declaration)) if n.type == NodeType.ENTRYPOINT: if var.name in init_vars: candidates.append(init_vars[var.name]) assert candidates return max(candidates, key=lambda v: v.index) def is_used_later(initial_node, variable): # TODO: does not handle the case where its read and written in the declaration node # It can be problematic if this happens in a loop/if structure # Ex: # for(;true;){ # if(true){ # uint a = a; # } # .. to_explore = {initial_node} explored = set() while to_explore: node = to_explore.pop() explored.add(node) if isinstance(variable, LocalVariable): if any(v.name == variable.name for v in node.local_variables_read): return True if any(v.name == variable.name for v in node.local_variables_written): return False if isinstance(variable, StateVariable): if any( v.name == variable.name and v.contract == variable.contract for v in node.state_variables_read ): return True if any( v.name == variable.name and v.contract == variable.contract for v in node.state_variables_written ): return False for son in node.sons: if not son in explored: to_explore.add(son) return False # endregion ################################################################################### ################################################################################### # region Update operation ################################################################################### ################################################################################### def update_lvalue( new_ir, node, local_variables_instances, all_local_variables_instances, state_variables_instances, all_state_variables_instances, ): if isinstance(new_ir, OperationWithLValue): lvalue = new_ir.lvalue update_through_ref = False if isinstance(new_ir, (Assignment, Binary)): if isinstance(lvalue, ReferenceVariable): update_through_ref = True while isinstance(lvalue, ReferenceVariable): lvalue = lvalue.points_to if isinstance(lvalue, (LocalIRVariable, StateIRVariable)): if isinstance(lvalue, LocalIRVariable): new_var = LocalIRVariable(lvalue) new_var.index = all_local_variables_instances[lvalue.name].index + 1 all_local_variables_instances[lvalue.name] = new_var local_variables_instances[lvalue.name] = new_var else: new_var = StateIRVariable(lvalue) new_var.index = all_state_variables_instances[lvalue.canonical_name].index + 1 all_state_variables_instances[lvalue.canonical_name] = new_var state_variables_instances[lvalue.canonical_name] = new_var if update_through_ref: phi_operation = Phi(new_var, {node}) phi_operation.rvalues = [lvalue] node.add_ssa_ir(phi_operation) if not isinstance(new_ir.lvalue, ReferenceVariable): new_ir.lvalue = new_var else: to_update = new_ir.lvalue while isinstance(to_update.points_to, ReferenceVariable): to_update = to_update.points_to to_update.points_to = new_var # endregion ################################################################################### ################################################################################### # region Initialization ################################################################################### ################################################################################### def initiate_all_local_variables_instances( nodes, local_variables_instances, all_local_variables_instances ): for node in nodes: if node.variable_declaration: new_var = LocalIRVariable(node.variable_declaration) if new_var.name in all_local_variables_instances: new_var.index = all_local_variables_instances[new_var.name].index + 1 local_variables_instances[node.variable_declaration.name] = new_var all_local_variables_instances[node.variable_declaration.name] = new_var # endregion ################################################################################### ################################################################################### # region Phi Operations ################################################################################### ################################################################################### def fix_phi_rvalues_and_storage_ref( node, local_variables_instances, all_local_variables_instances, state_variables_instances, all_state_variables_instances, init_local_variables_instances, ): for ir in node.irs_ssa: if isinstance(ir, (Phi)) and not ir.rvalues: variables = [ last_name(dst, ir.lvalue, init_local_variables_instances) for dst in ir.nodes ] ir.rvalues = variables if isinstance(ir, (Phi, PhiCallback)): if isinstance(ir.lvalue, LocalIRVariable): if ir.lvalue.is_storage: l = [v.refers_to for v in ir.rvalues] l = [item for sublist in l for item in sublist] ir.lvalue.refers_to = set(l) if isinstance(ir, (Assignment, Binary)): if isinstance(ir.lvalue, ReferenceVariable): origin = ir.lvalue.points_to_origin if isinstance(origin, LocalIRVariable): if origin.is_storage: for refers_to in origin.refers_to: phi_ir = Phi(refers_to, {node}) phi_ir.rvalues = [origin] node.add_ssa_ir(phi_ir) update_lvalue( phi_ir, node, local_variables_instances, all_local_variables_instances, state_variables_instances, all_state_variables_instances, ) for succ in node.dominator_successors: fix_phi_rvalues_and_storage_ref( succ, dict(local_variables_instances), all_local_variables_instances, dict(state_variables_instances), all_state_variables_instances, init_local_variables_instances, ) def add_phi_origins(node, local_variables_definition, state_variables_definition): # Add new key to local_variables_definition # The key is the variable_name # The value is (variable_instance, the node where its written) # We keep the instance as we want to avoid to add __hash__ on v.name in Variable # That might work for this used, but could create collision for other uses local_variables_definition = dict( local_variables_definition, **{v.name: (v, node) for v in node.local_variables_written}, ) state_variables_definition = dict( state_variables_definition, **{v.canonical_name: (v, node) for v in node.state_variables_written}, ) # For unini variable declaration if ( node.variable_declaration and not node.variable_declaration.name in local_variables_definition ): local_variables_definition[node.variable_declaration.name] = ( node.variable_declaration, node, ) # filter length of successors because we have node with one successor # while most of the ssa textbook would represent following nodes as one if node.dominance_frontier and len(node.dominator_successors) != 1: for phi_node in node.dominance_frontier: for _, (variable, n) in local_variables_definition.items(): phi_node.add_phi_origin_local_variable(variable, n) for _, (variable, n) in state_variables_definition.items(): phi_node.add_phi_origin_state_variable(variable, n) if not node.dominator_successors: return for succ in node.dominator_successors: add_phi_origins(succ, local_variables_definition, state_variables_definition) # endregion ################################################################################### ################################################################################### # region IR copy ################################################################################### ################################################################################### def get( variable, local_variables_instances, state_variables_instances, temporary_variables_instances, reference_variables_instances, tuple_variables_instances, all_local_variables_instances, ): # variable can be None # for example, on LowLevelCall, ir.lvalue can be none if variable is None: return None if isinstance(variable, LocalVariable): if variable.name in local_variables_instances: return local_variables_instances[variable.name] new_var = LocalIRVariable(variable) local_variables_instances[variable.name] = new_var all_local_variables_instances[variable.name] = new_var return new_var if isinstance(variable, StateVariable) and variable.canonical_name in state_variables_instances: return state_variables_instances[variable.canonical_name] if isinstance(variable, ReferenceVariable): if not variable.index in reference_variables_instances: new_variable = ReferenceVariableSSA(variable) if variable.points_to: new_variable.points_to = get( variable.points_to, local_variables_instances, state_variables_instances, temporary_variables_instances, reference_variables_instances, tuple_variables_instances, all_local_variables_instances, ) new_variable.set_type(variable.type) reference_variables_instances[variable.index] = new_variable return reference_variables_instances[variable.index] if isinstance(variable, TemporaryVariable): if not variable.index in temporary_variables_instances: new_variable = TemporaryVariableSSA(variable) new_variable.set_type(variable.type) temporary_variables_instances[variable.index] = new_variable return temporary_variables_instances[variable.index] if isinstance(variable, TupleVariable): if not variable.index in tuple_variables_instances: new_variable = TupleVariableSSA(variable) new_variable.set_type(variable.type) tuple_variables_instances[variable.index] = new_variable return tuple_variables_instances[variable.index] assert isinstance( variable, ( Constant, SolidityVariable, Contract, Enum, SolidityFunction, Structure, Function, Type, SolidityImportPlaceHolder, TopLevelVariable, ), ) # type for abi.decode(.., t) return variable def get_variable(ir, f, *instances): # pylint: disable=no-value-for-parameter variable = f(ir) variable = get(variable, *instances) return variable def _get_traversal(values, *instances): ret = [] # pylint: disable=no-value-for-parameter for v in values: if isinstance(v, list): v = _get_traversal(v, *instances) else: v = get(v, *instances) ret.append(v) return ret def get_arguments(ir, *instances): return _get_traversal(ir.arguments, *instances) def get_rec_values(ir, f, *instances): # Use by InitArray and NewArray # Potential recursive array(s) ori_init_values = f(ir) return _get_traversal(ori_init_values, *instances) def copy_ir(ir, *instances): """ Args: ir (Operation) local_variables_instances(dict(str -> LocalVariable)) state_variables_instances(dict(str -> StateVariable)) temporary_variables_instances(dict(int -> Variable)) reference_variables_instances(dict(int -> Variable)) Note: temporary and reference can be indexed by int, as they dont need phi functions """ if isinstance(ir, Assignment): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) rvalue = get_variable(ir, lambda x: x.rvalue, *instances) variable_return_type = ir.variable_return_type return Assignment(lvalue, rvalue, variable_return_type) if isinstance(ir, Binary): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) variable_left = get_variable(ir, lambda x: x.variable_left, *instances) variable_right = get_variable(ir, lambda x: x.variable_right, *instances) operation_type = ir.type return Binary(lvalue, variable_left, variable_right, operation_type) if isinstance(ir, CodeSize): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) value = get_variable(ir, lambda x: x.value, *instances) return CodeSize(value, lvalue) if isinstance(ir, Condition): val = get_variable(ir, lambda x: x.value, *instances) return Condition(val) if isinstance(ir, Delete): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) variable = get_variable(ir, lambda x: x.variable, *instances) return Delete(lvalue, variable) if isinstance(ir, EventCall): name = ir.name new_ir = EventCall(name) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, HighLevelCall): # include LibraryCall destination = get_variable(ir, lambda x: x.destination, *instances) function_name = ir.function_name nbr_arguments = ir.nbr_arguments lvalue = get_variable(ir, lambda x: x.lvalue, *instances) type_call = ir.type_call if isinstance(ir, LibraryCall): new_ir = LibraryCall(destination, function_name, nbr_arguments, lvalue, type_call) else: new_ir = HighLevelCall(destination, function_name, nbr_arguments, lvalue, type_call) new_ir.call_id = ir.call_id new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances) new_ir.call_gas = get_variable(ir, lambda x: x.call_gas, *instances) new_ir.arguments = get_arguments(ir, *instances) new_ir.function = ir.function return new_ir if isinstance(ir, Index): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) variable_left = get_variable(ir, lambda x: x.variable_left, *instances) variable_right = get_variable(ir, lambda x: x.variable_right, *instances) index_type = ir.index_type return Index(lvalue, variable_left, variable_right, index_type) if isinstance(ir, InitArray): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) init_values = get_rec_values(ir, lambda x: x.init_values, *instances) return InitArray(init_values, lvalue) if isinstance(ir, InternalCall): function = ir.function nbr_arguments = ir.nbr_arguments lvalue = get_variable(ir, lambda x: x.lvalue, *instances) type_call = ir.type_call new_ir = InternalCall(function, nbr_arguments, lvalue, type_call) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, InternalDynamicCall): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) function = get_variable(ir, lambda x: x.function, *instances) function_type = ir.function_type new_ir = InternalDynamicCall(lvalue, function, function_type) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, LowLevelCall): destination = get_variable(ir, lambda x: x.destination, *instances) function_name = ir.function_name nbr_arguments = ir.nbr_arguments lvalue = get_variable(ir, lambda x: x.lvalue, *instances) type_call = ir.type_call new_ir = LowLevelCall(destination, function_name, nbr_arguments, lvalue, type_call) new_ir.call_id = ir.call_id new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances) new_ir.call_gas = get_variable(ir, lambda x: x.call_gas, *instances) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, Member): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) variable_left = get_variable(ir, lambda x: x.variable_left, *instances) variable_right = get_variable(ir, lambda x: x.variable_right, *instances) return Member(variable_left, variable_right, lvalue) if isinstance(ir, NewArray): depth = ir.depth array_type = ir.array_type lvalue = get_variable(ir, lambda x: x.lvalue, *instances) new_ir = NewArray(depth, array_type, lvalue) new_ir.arguments = get_rec_values(ir, lambda x: x.arguments, *instances) return new_ir if isinstance(ir, NewElementaryType): new_type = ir.type lvalue = get_variable(ir, lambda x: x.lvalue, *instances) new_ir = NewElementaryType(new_type, lvalue) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, NewContract): contract_name = ir.contract_name lvalue = get_variable(ir, lambda x: x.lvalue, *instances) new_ir = NewContract(contract_name, lvalue) new_ir.arguments = get_arguments(ir, *instances) new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances) new_ir.call_salt = get_variable(ir, lambda x: x.call_salt, *instances) return new_ir if isinstance(ir, NewStructure): structure = ir.structure lvalue = get_variable(ir, lambda x: x.lvalue, *instances) new_ir = NewStructure(structure, lvalue) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, Nop): return Nop() if isinstance(ir, Return): values = get_rec_values(ir, lambda x: x.values, *instances) return Return(values) if isinstance(ir, Send): destination = get_variable(ir, lambda x: x.destination, *instances) value = get_variable(ir, lambda x: x.call_value, *instances) lvalue = get_variable(ir, lambda x: x.lvalue, *instances) return Send(destination, value, lvalue) if isinstance(ir, SolidityCall): function = ir.function nbr_arguments = ir.nbr_arguments lvalue = get_variable(ir, lambda x: x.lvalue, *instances) type_call = ir.type_call new_ir = SolidityCall(function, nbr_arguments, lvalue, type_call) new_ir.arguments = get_arguments(ir, *instances) return new_ir if isinstance(ir, Transfer): destination = get_variable(ir, lambda x: x.destination, *instances) value = get_variable(ir, lambda x: x.call_value, *instances) return Transfer(destination, value) if isinstance(ir, TypeConversion): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) variable = get_variable(ir, lambda x: x.variable, *instances) variable_type = ir.type return TypeConversion(lvalue, variable, variable_type) if isinstance(ir, Unary): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) rvalue = get_variable(ir, lambda x: x.rvalue, *instances) operation_type = ir.type return Unary(lvalue, rvalue, operation_type) if isinstance(ir, Unpack): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) tuple_var = get_variable(ir, lambda x: x.tuple, *instances) idx = ir.index return Unpack(lvalue, tuple_var, idx) if isinstance(ir, Length): lvalue = get_variable(ir, lambda x: x.lvalue, *instances) value = get_variable(ir, lambda x: x.value, *instances) return Length(value, lvalue) raise SlithIRError(f"Impossible ir copy on {ir} ({type(ir)})") # endregion
32,701
Python
.py
738
34.97561
113
0.590005
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,348
utils.py
NioTheFirst_ScType/slither/slithir/utils/utils.py
from slither.core.variables.local_variable import LocalVariable from slither.core.variables.state_variable import StateVariable from slither.core.declarations.solidity_variables import SolidityVariable from slither.core.variables.top_level_variable import TopLevelVariable from slither.slithir.variables.temporary import TemporaryVariable from slither.slithir.variables.constant import Constant from slither.slithir.variables.reference import ReferenceVariable from slither.slithir.variables.tuple import TupleVariable def is_valid_rvalue(v): return isinstance( v, ( StateVariable, LocalVariable, TopLevelVariable, TemporaryVariable, Constant, SolidityVariable, ReferenceVariable, ), ) def is_valid_lvalue(v): return isinstance( v, ( StateVariable, LocalVariable, TemporaryVariable, ReferenceVariable, TupleVariable, ), )
1,036
Python
.py
32
24.6875
73
0.700401
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,349
reference_ssa.py
NioTheFirst_ScType/slither/slithir/variables/reference_ssa.py
""" This class is used for the SSA version of slithIR It is similar to the non-SSA version of slithIR as the ReferenceVariable are in SSA form in both version """ from slither.slithir.variables.reference import ReferenceVariable class ReferenceVariableSSA(ReferenceVariable): # pylint: disable=too-few-public-methods def __init__(self, reference): super().__init__(reference.node, reference.index) self._non_ssa_version = reference @property def non_ssa_version(self): return self._non_ssa_version
551
Python
.py
13
37.384615
88
0.73221
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,350
state_variable.py
NioTheFirst_ScType/slither/slithir/variables/state_variable.py
from slither.core.variables.state_variable import StateVariable from slither.slithir.variables.variable import SlithIRVariable class StateIRVariable( StateVariable, SlithIRVariable ): # pylint: disable=too-many-instance-attributes def __init__(self, state_variable): assert isinstance(state_variable, StateVariable) super().__init__() # initiate ChildContract self.set_contract(state_variable.contract) # initiate Variable self._name = state_variable.name self._initial_expression = state_variable.expression self._type = state_variable.type self._initialized = state_variable.initialized self._visibility = state_variable.visibility self._is_constant = state_variable.is_constant self._index = 0 # keep un-ssa version if isinstance(state_variable, StateIRVariable): self._non_ssa_version = state_variable.non_ssa_version else: self._non_ssa_version = state_variable @property def index(self): return self._index @index.setter def index(self, idx): self._index = idx @property def non_ssa_version(self): return self._non_ssa_version @property def ssa_name(self): return f"{self._name}_{self.index}"
1,327
Python
.py
35
30.428571
66
0.676034
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,351
temporary.py
NioTheFirst_ScType/slither/slithir/variables/temporary.py
from typing import TYPE_CHECKING from slither.core.children.child_node import ChildNode from slither.core.variables.variable import Variable if TYPE_CHECKING: from slither.core.cfg.node import Node class TemporaryVariable(ChildNode, Variable): def __init__(self, node: "Node", index=None): super().__init__() if index is None: self._index = node.compilation_unit.counter_slithir_temporary node.compilation_unit.counter_slithir_temporary += 1 else: self._index = index self._node = node @property def index(self): return self._index @index.setter def index(self, idx): self._index = idx @property def name(self): return f"TMP_{self.index}" def __str__(self): return self.name
819
Python
.py
25
26
73
0.655216
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,352
__init__.py
NioTheFirst_ScType/slither/slithir/variables/__init__.py
from .constant import Constant from .reference import ReferenceVariable from .reference_ssa import ReferenceVariableSSA from .temporary import TemporaryVariable from .temporary_ssa import TemporaryVariableSSA from .tuple import TupleVariable from .tuple_ssa import TupleVariableSSA from .local_variable import LocalIRVariable from .state_variable import StateIRVariable
370
Python
.py
9
40.111111
47
0.886427
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,353
local_variable.py
NioTheFirst_ScType/slither/slithir/variables/local_variable.py
from slither.core.variables.local_variable import LocalVariable from slither.slithir.variables.temporary import TemporaryVariable from slither.slithir.variables.variable import SlithIRVariable class LocalIRVariable( LocalVariable, SlithIRVariable ): # pylint: disable=too-many-instance-attributes def __init__(self, local_variable): assert isinstance(local_variable, LocalVariable) super().__init__() # initiate ChildContract self.set_function(local_variable.function) # initiate Variable self._name = local_variable.name self._initial_expression = local_variable.expression self._type = local_variable.type self._initialized = local_variable.initialized self._visibility = local_variable.visibility self._is_constant = local_variable.is_constant # initiate LocalVariable self._location = local_variable.location self._is_storage = local_variable.is_storage self._index = 0 # Additional field # points to state variables self._refers_to = set() # keep un-ssa version if isinstance(local_variable, LocalIRVariable): self._non_ssa_version = local_variable.non_ssa_version else: self._non_ssa_version = local_variable @property def index(self): return self._index @index.setter def index(self, idx): self._index = idx @property def refers_to(self): if self.is_storage: return self._refers_to return set() @refers_to.setter def refers_to(self, variables): self._refers_to = variables @property def non_ssa_version(self): return self._non_ssa_version def add_refers_to(self, variable): # It is a temporaryVariable if its the return of a new .. # ex: string[] memory dynargs = new string[](1); assert isinstance(variable, (SlithIRVariable, TemporaryVariable)) self._refers_to.add(variable) @property def ssa_name(self): if self.is_storage: return f"{self._name}_{self.index} (-> {[v.name for v in self.refers_to]})" return f"{self._name}_{self.index}"
2,235
Python
.py
57
31.403509
87
0.661425
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,354
temporary_ssa.py
NioTheFirst_ScType/slither/slithir/variables/temporary_ssa.py
""" This class is used for the SSA version of slithIR It is similar to the non-SSA version of slithIR as the TemporaryVariable are in SSA form in both version """ from slither.slithir.variables.temporary import TemporaryVariable class TemporaryVariableSSA(TemporaryVariable): # pylint: disable=too-few-public-methods def __init__(self, temporary): super().__init__(temporary.node, temporary.index) self._non_ssa_version = temporary @property def non_ssa_version(self): return self._non_ssa_version
551
Python
.py
13
37.384615
88
0.73221
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,355
constant.py
NioTheFirst_ScType/slither/slithir/variables/constant.py
from functools import total_ordering from slither.core.solidity_types.elementary_type import ElementaryType, Int, Uint from slither.slithir.variables.variable import SlithIRVariable from slither.utils.arithmetic import convert_subdenomination from slither.utils.integer_conversion import convert_string_to_int @total_ordering class Constant(SlithIRVariable): def __init__( self, val, constant_type=None, subdenomination=None ): # pylint: disable=too-many-branches super().__init__() assert isinstance(val, str) self._original_value = val self._subdenomination = subdenomination if subdenomination: val = str(convert_subdenomination(val, subdenomination)) if constant_type: # pylint: disable=too-many-nested-blocks assert isinstance(constant_type, ElementaryType) self._type = constant_type if constant_type.type in Int + Uint + ["address"]: self._val = convert_string_to_int(val) elif constant_type.type == "bool": self._val = (val == "true") | (val == "True") else: self._val = val else: if val.isdigit(): self._type = ElementaryType("uint256") self._val = convert_string_to_int(val) else: self._type = ElementaryType("string") self._val = val @property def value(self): """ Return the value. If the expression was an hexadecimal delcared as hex'...' return a str Returns: (str | int | bool) """ return self._val @property def original_value(self): """ Return the string representation of the value :return: str """ return self._original_value def __str__(self): return str(self.value) @property def name(self): return str(self) def __eq__(self, other): return self.value == other def __ne__(self, other): return self.value != other def __lt__(self, other): return self.value < other def __repr__(self): return f"{str(self.value)}" def __hash__(self) -> int: return self._val.__hash__()
2,297
Python
.py
64
26.96875
81
0.594229
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,356
reference.py
NioTheFirst_ScType/slither/slithir/variables/reference.py
from typing import TYPE_CHECKING from slither.core.children.child_node import ChildNode from slither.core.declarations import Contract, Enum, SolidityVariable, Function from slither.core.variables.variable import Variable if TYPE_CHECKING: from slither.core.cfg.node import Node class ReferenceVariable(ChildNode, Variable): def __init__(self, node: "Node", index=None): super().__init__() if index is None: self._index = node.compilation_unit.counter_slithir_reference node.compilation_unit.counter_slithir_reference += 1 else: self._index = index self._points_to = None self._node = node @property def index(self): return self._index @index.setter def index(self, idx): self._index = idx @property def points_to(self): """ Return the variable pointer by the reference It is the left member of a Index or Member operator """ return self._points_to @property def points_to_origin(self): points = self.points_to while isinstance(points, ReferenceVariable): points = points.points_to return points @points_to.setter def points_to(self, points_to): # Can only be a rvalue of # Member or Index operator # pylint: disable=import-outside-toplevel from slither.slithir.utils.utils import is_valid_lvalue assert is_valid_lvalue(points_to) or isinstance( points_to, (SolidityVariable, Contract, Enum) ) self._points_to = points_to @property def name(self): return f"REF_{self.index}" # overide of core.variables.variables # reference can have Function has a type # to handle the function selector def set_type(self, t): if not isinstance(t, Function): super().set_type(t) else: self._type = t def __str__(self): return self.name
2,002
Python
.py
58
26.931034
80
0.64456
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,357
tuple_ssa.py
NioTheFirst_ScType/slither/slithir/variables/tuple_ssa.py
""" This class is used for the SSA version of slithIR It is similar to the non-SSA version of slithIR as the TupleVariable are in SSA form in both version """ from slither.slithir.variables.tuple import TupleVariable class TupleVariableSSA(TupleVariable): # pylint: disable=too-few-public-methods def __init__(self, t): super().__init__(t.node, t.index) self._non_ssa_version = t @property def non_ssa_version(self): return self._non_ssa_version
499
Python
.py
13
33.384615
80
0.70332
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,358
tuple.py
NioTheFirst_ScType/slither/slithir/variables/tuple.py
from typing import TYPE_CHECKING from slither.core.children.child_node import ChildNode from slither.slithir.variables.variable import SlithIRVariable if TYPE_CHECKING: from slither.core.cfg.node import Node class TupleVariable(ChildNode, SlithIRVariable): def __init__(self, node: "Node", index=None): super().__init__() if index is None: self._index = node.compilation_unit.counter_slithir_tuple node.compilation_unit.counter_slithir_tuple += 1 else: self._index = index self._node = node @property def index(self): return self._index @index.setter def index(self, idx): self._index = idx @property def name(self): return f"TUPLE_{self.index}" def __str__(self): return self.name
827
Python
.py
25
26.28
69
0.65826
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,359
variable.py
NioTheFirst_ScType/slither/slithir/variables/variable.py
from slither.core.variables.variable import Variable class SlithIRVariable(Variable): token_type = -1; def __init__(self): super().__init__() self._index = 0 @property def ssa_name(self): return self.name def __str__(self): return self.ssa_name def set_token_type(t): token_type = t
352
Python
.py
13
20.769231
52
0.607784
NioTheFirst/ScType
8
4
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,360
tracepicture.py
jianhuxwx_invisomark/tracepicture.py
import requests def fetch_google_lens_page_token(api_key, image_url, language=None, country=None, no_cache=None, async_param=None): """ Fetches the page token for Google Lens Image Sources API using SerpApi. :param api_key: Your SerpApi private key. :param image_url: URL of the image to perform the Google Lens search. :param language: Optional. Language for the search (e.g., 'en'). :param country: Optional. Country for the search (e.g., 'us'). :param no_cache: Optional. Whether to bypass cache (True or False). :param async_param: Optional. Whether to submit search asynchronously (True or False). :return: Page token for the image sources search. """ base_url = "https://serpapi.com/search" params = { "engine": "google_lens", "api_key": api_key, "url": image_url, "hl": language, "country": country, "no_cache": no_cache, "async": async_param } # Remove None values from params params = {k: v for k, v in params.items() if v is not None} response = requests.get(base_url, params=params) response.raise_for_status() search_results = response.json() return search_results.get("image_sources_search", {}).get("page_token") def fetch_google_lens_image_sources(api_key, page_token): """ Fetches image sources from Google Lens using SerpApi with a given page token. :param api_key: Your SerpApi private key. :param page_token: Token to retrieve image sources. :return: Parsed JSON data of the image sources. """ base_url = "https://serpapi.com/search" params = { "engine": "google_lens_image_sources", "api_key": api_key, "page_token": page_token } response = requests.get(base_url, params=params) response.raise_for_status() return response.json() # Example usage #api_key = "cbffeb8fa1dd8ae8549f588fc59b30ced4cf50b812435964648de4aff88aa360" # Replace with your actual API key #image_url = "https://d.furaffinity.net/art/jianhu/1677393776/1677393776.jianhu_2631660065489__pic_hd.jpg" # Replace with your actual image URL # Fetch page token and image sources #page_token = fetch_google_lens_page_token(api_key, image_url) #image_sources_results = fetch_google_lens_image_sources(api_key, page_token) #print(image_sources_results)
2,350
Python
.py
51
40.823529
144
0.697288
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,361
ipfs.py
jianhuxwx_invisomark/ipfs.py
import requests import json def upload_to_ipfs(file_path): url = "https://api.nft.storage/upload" headers = { "Authorization": f"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDljNzAyNDM4NjQ4MTg0NERCN2FkQzdEMDhjNzYyRjY1NEFEOWY5NGQiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY5OTkzODUyNTQ5MSwibmFtZSI6IjEyMyJ9.6GRy_UZoDeA78QdRiADStFZLnuZkRof5qKlLmhMR0-4", "Content-Type": "application/octet-stream" } with open(file_path, 'rb') as f: response = requests.post(url, headers=headers, data=f) if response.status_code == 200: return json.loads(response.text) else: return f"Error: {response.status_code}" # 使用示例 #api_key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDljNzAyNDM4NjQ4MTg0NERCN2FkQzdEMDhjNzYyRjY1NEFEOWY5NGQiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY5OTkzODUyNTQ5MSwibmFtZSI6IjEyMyJ9.6GRy_UZoDeA78QdRiADStFZLnuZkRof5qKlLmhMR0-4" # 替换为您的API密钥 #file_path = "/Users/david/Desktop/Code/ATP/vulpinium_1.jpeg" # 替换为您要上传的文件路径 #result = upload_to_ipfs(file_path) #print(result)
1,133
Python
.py
19
52.578947
269
0.803387
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,362
basic_watermark.py
jianhuxwx_invisomark/basic_watermark.py
from PIL import Image, ImageDraw, ImageFont def add_watermark(input_image_path, output_image_path, watermark_text): # 打开图片 image = Image.open(input_image_path) width, height = image.size # 创建一个可以在图片上绘图的对象 draw = ImageDraw.Draw(image) # 设置较大的字体 font = ImageFont.truetype("arial.ttf", 36) # 使用Arial字体,字号为36 # 确定文本位置(左下角) x = 10 y = height - 50 # 距离底部50像素 # 获取图片底部边缘的平均颜色 bottom_edge = image.crop((0, height - 50, width, height)) pixels = list(bottom_edge.getdata()) average_color = sum(sum(pixel) / 3 for pixel in pixels) / len(pixels) # 根据平均颜色选择文本颜色 text_color = (0, 0, 0) if average_color > 128 else (255, 255, 255) # 在图片上添加文本 draw.text((x, y), watermark_text, font=font, fill=text_color) # 保存图片 image.save(output_image_path) # 使用示例 #add_watermark('/Users/david/Desktop/Code/ATP/vulpinium_1.jpeg', '/Users/david/Desktop/Code/ATP/vulpinium_1_new.jpeg', '© 2023 Your Name')
1,148
Python
.py
24
35.416667
138
0.67957
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,363
blind.py
jianhuxwx_invisomark/blind.py
from blind_watermark import WaterMark def embed_watermark(original_image_path, watermark_content, output_image_path): bwm = WaterMark(password_img=1, password_wm=1) bwm.read_img(original_image_path) bwm.read_wm(watermark_content, mode='str') bwm.embed(output_image_path) len_wm = len(bwm.wm_bit) print('Put down the length of wm_bit: {}'.format(len_wm)) return len_wm def extract_watermark(embedded_image_path, wm_length): bwm = WaterMark(password_img=1, password_wm=1) wm_extract = bwm.extract(embedded_image_path, wm_shape=wm_length, mode='str') print(wm_extract) return wm_extract # 使用示例 # 嵌入水印 #wm_length = embed_watermark('/Users/david/Desktop/Code/ATP/11.jpg', 'Keyfox', '/Users/david/Desktop/Code/ATP/11.jpg') # 提取水印 #extracted_wm = extract_watermark('/Users/david/Desktop/Code/ATP/vulpinium_1_watermarked.png', 87) #print(extracted_wm)
916
Python
.py
20
41.2
118
0.735023
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,364
blur.py
jianhuxwx_invisomark/blur.py
from PIL import Image, ImageFilter def blur_image(input_image_path, output_image_path, blur_amount): # 打开图片 image = Image.open(input_image_path) # 应用模糊效果 blurred_image = image.filter(ImageFilter.GaussianBlur(blur_amount)) # 保存模糊后的图片 blurred_image.save(output_image_path) # 使用示例 #blur_image('/Users/david/Desktop/Code/ATP/11_watermarked.png', '/Users/david/Desktop/Code/ATP/11_watermarked.png', 10000000)
476
Python
.py
10
39.4
125
0.751196
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,365
line.py
jianhuxwx_invisomark/line.py
import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont def extract_edges(image_path): # 读取图片并转换为灰度图 image = cv2.imread(image_path, cv2.IMREAD_COLOR) # 确保图像始终为彩色图像 if image is None: raise ValueError("无法加载图像,请检查路径和文件格式。") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 使用Canny算法提取边缘 edges = cv2.Canny(gray, 100, 200) return edges def approximate_text_size(text, font_size): return (font_size // 2 * len(text), font_size) def write_text_along_path(image_path, text, output_path, font_size=10, font_color=(255, 0, 0, 255)): # 默认颜色现在包含透明度 edges = extract_edges(image_path) image = Image.open(image_path).convert("RGBA") # 转换为带透明度的模式 overlay = Image.new("RGBA", image.size, (255, 255, 255, 0)) # 创建透明覆盖层 draw = ImageDraw.Draw(overlay) font = ImageFont.truetype("arial.ttf", font_size) occupied = np.zeros(edges.shape, dtype=bool) def can_place_text(x, y, text): size = approximate_text_size(text, font_size) if x + size[0] >= edges.shape[1] or y + size[1] >= edges.shape[0]: return False for i in range(size[1]): for j in range(size[0]): if occupied[y + i, x + j]: return False return True def place_text(x, y, text): draw.text((x, y), text, font=font, fill=font_color) size = approximate_text_size(text, font_size) for i in range(size[1]): for j in range(size[0]): occupied[y + i, x + j] = True for y in range(edges.shape[0]): for x in range(edges.shape[1]): if edges[y, x] != 0 and can_place_text(x, y, text): place_text(x, y, text) combined = Image.alpha_composite(image, overlay) combined.save(output_path) #write_text_along_path('/Users/david/Desktop/Code/ATP/11.jpeg', 'Keyfox', '/Users/david/Desktop/Code/ATP/111.png', font_size=8, font_color=(0, 128, 255, 50)) # 使用半透明的蓝色
2,144
Python
.py
43
38.534884
169
0.626757
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,366
metadata.py
jianhuxwx_invisomark/metadata.py
from PIL import Image from PIL.ExifTags import TAGS def get_reversed_tags(): return {value: key for key, value in TAGS.items()} def add_metadata(image_path, metadata): image = Image.open(image_path) exif_data = image.getexif() reversed_tags = get_reversed_tags() for tag, value in metadata.items(): if tag in reversed_tags: exif_data[reversed_tags[tag]] = value image.save(image_path, exif=exif_data) def read_metadata(image_path): image = Image.open(image_path) exif_data = image.getexif() readable_exif = {TAGS[key]: value for key, value in exif_data.items() if key in TAGS} return readable_exif # 使用示例 #metadata = read_metadata('/Users/david/Desktop/Code/ATP/logo 2_watermarked.png') #print(metadata) # 使用示例 #add_metadata('/Users/david/Desktop/Code/ATP/vulpinium_1.jpeg', {'Artist': 'Your Name', 'Software': 'Your Software'})
914
Python
.py
22
36.681818
117
0.708189
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,367
full_watermark.py
jianhuxwx_invisomark/full_watermark.py
from PIL import Image, ImageDraw, ImageFont def estimate_text_size(text, font_size): """估算文本尺寸的简化方法。""" average_char_width = font_size * 0.6 # 假设每个字符的平均宽度 text_width = int(average_char_width * len(text)) text_height = font_size return text_width, text_height def add_watermark(input_image_path, output_image_path, watermark_text, font_size=20): # 打开图片 original_image = Image.open(input_image_path).convert('RGBA') width, height = original_image.size # 创建一个透明的水印层 watermark = Image.new('RGBA', (width, height), (0, 0, 0, 0)) watermark_draw = ImageDraw.Draw(watermark) # 创建字体对象 font = ImageFont.load_default() # 估算文本大小 text_width, text_height = estimate_text_size(watermark_text, font_size) # 在整个图片上重复添加水印 for x in range(0, width, text_width): for y in range(0, height, text_height): watermark_draw.text((x, y), watermark_text, fill=(255, 255, 255, 128), font=font) # 将水印层合并到原始图片上 watermarked_image = Image.alpha_composite(original_image, watermark) # 保存添加了水印的图片 watermarked_image.save(output_image_path, 'PNG') # 使用示例 #add_watermark('/Users/david/Desktop/Code/ATP/vulpinium_11.jpeg', '/Users/david/Desktop/Code/ATP/vulpinium_111.jpeg', 'Your Watermark Text')
1,446
Python
.py
28
40.392857
140
0.698785
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,368
signature.py
jianhuxwx_invisomark/signature.py
import hashlib from cryptography.fernet import Fernet import base64 import sys def compute_hash(file_path): hasher = hashlib.sha256() with open(file_path, 'rb') as file: buf = file.read() hasher.update(buf) return hasher.digest() def encrypt_hash(hash_value, key): fernet = Fernet(key) return fernet.encrypt(hash_value) def decrypt_hash(encrypted_hash, key): fernet = Fernet(key) return fernet.decrypt(encrypted_hash) def save_encrypted_hash(file_path, encrypted_hash): with open(file_path, 'wb') as file: file.write(encrypted_hash) def load_encrypted_hash(file_path): with open(file_path, 'rb') as file: return file.read() def hash_similarity(hash1, hash2): return sum(x == y for x, y in zip(hash1, hash2)) / len(hash1) def generate_signature(image_path, key, output_file): hash_value = compute_hash(image_path) encrypted_hash = encrypt_hash(hash_value, key) save_encrypted_hash(output_file, encrypted_hash) def verify_signature(image_path, key, signature_file): original_hash = decrypt_hash(load_encrypted_hash(signature_file), key) new_hash = compute_hash(image_path) similarity = hash_similarity(original_hash, new_hash) return similarity > 0.9 def generate_key_from_string(input_string): # 使用SHA-256哈希函数处理输入字符串 hash = hashlib.sha256(input_string.encode()).digest() # 将哈希值转换为base64编码 return base64.urlsafe_b64encode(hash) #custom_string = "hello_world" #key = generate_key_from_string(custom_string) #generate_signature('/Users/david/Desktop/Code/ATP/vulpinium_11.jpeg', key, '/Users/david/Desktop/Code/ATP/signature.pctf') # 验证 #result = verify_signature('/Users/david/Desktop/Code/ATP/vulpinium_1.jpeg', key, '/Users/david/Desktop/Code/ATP/signature.pctf') #print("验证成功" if result else "验证失败")
1,892
Python
.py
44
37.636364
129
0.731941
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,369
main.py
jianhuxwx_invisomark/main.py
''' <INVISOMARK - Greatest Watermark Software> Copyright (C) <2023> <YuexuChen> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ''' import customtkinter as ctk import tkinter.filedialog as filedialog import tkinter.messagebox as messagebox from PIL import Image, ImageTk import os import basic_watermark import full_watermark import line import metadata import signature import blind import blur import ipfs import webbrowser import tracepicture import tkinter as tk import tkinter.scrolledtext as scrolledtext import requests import re import io class CollapsiblePane(ctk.CTkFrame): def __init__(self, parent, title="", *args, **kwargs): super().__init__(parent, *args, **kwargs) self.title = title self.toggle_button = ctk.CTkButton(self, text=self.title, command=self.toggle) self.toggle_button.pack(fill="x", pady=2) self.content_frame = ctk.CTkFrame(self) self.content_visible = False def toggle(self): if self.content_visible: self.content_frame.pack_forget() self.content_visible = False else: self.content_frame.pack(fill="x", expand=True) self.content_visible = True def add_widget(self, widget): widget.pack(fill="x", pady=2) #必要方法定义 def copy_to_clipboard(text): app.clipboard_clear() app.clipboard_append(text) messagebox.showinfo("复制成功", "已复制到剪贴板") #更新滑动条 def update_sliders(event=None): red_value_label.configure(text="红色:"+f"{red_slider.get():.0f}") green_value_label.configure(text="绿色:"+f"{green_slider.get():.0f}") blue_value_label.configure(text="蓝色:"+f"{blue_slider.get():.0f}") alpha_value_label.configure(text="透明度:"+f"{alpha_slider.get() / 10:.1f}") #选择文件 def choose_file(): file_path = filedialog.askopenfilename() if file_path: file_entry.set(file_path) update_output_path(file_path) update_image_preview(file_path) else: file_entry.set('') output_entry.set('') #更新输出文件路径 def update_output_path(input_path): base, ext = os.path.splitext(input_path) output_path = base + '_watermarked.png' output_entry.set(output_path) #更新实例 def update_image_preview(file_path): try: img = Image.open(file_path) img.thumbnail((200, 200)) img = ImageTk.PhotoImage(img) image_label.configure(image=img) image_label.image = img except Exception as e: image_label.configure(image='') image_label.text = '图片预览不可用' #获取图片路径 def get_working_file(): original = file_entry.get() watermarked = output_entry.get() if os.path.exists(original) or os.path.exists(watermarked): return watermarked if os.path.exists(watermarked) else original else: return None #应用水印 def apply_watermarks(): working_file = get_working_file() if not working_file: messagebox.showinfo("提示", "没有选择有效的文件。") return output_file = output_entry.get() try: #盲水印 if blind_watermark_check.get(): watermark_text = watermark_text_entry.get() blind_result = blind.embed_watermark(working_file, watermark_text, output_file) if isinstance(blind_result, tuple): blind_key = blind_result[0] blind_key_label.set(f"盲水印密钥(请妥善保管): {blind_key}") else: blind_key_label.set(f"盲水印密钥(请妥善保管): {blind_result}") working_file = output_file #线性水印 if line_watermark_check.get(): input_text = line_text_entry.get() font_size = int(font_size_entry.get()) red = int(red_slider.get()) green = int(green_slider.get()) blue = int(blue_slider.get()) alpha = alpha_slider.get() / 10 font_color = (red, green, blue, int(alpha * 255)) line.write_text_along_path(working_file, input_text, output_file, font_size=font_size, font_color=font_color) #满屏水印 if full_watermark_check.get(): full_watermark_text = full_watermark_text_entry.get() full_watermark.add_watermark(working_file, output_file, full_watermark_text) #基础水印 if basic_watermark_check.get(): basic_watermark_text = watermark_text_entry.get() basic_watermark.add_watermark(working_file, output_file, basic_watermark_text) #模糊图片 if blur_watermark_check.get(): blur_level = int(blur_level_entry.get()) blur.blur_image(working_file, output_file, blur_level) #元数据 if metadata_check.get(): artist = artist_entry.get() software = software_entry.get() image = Image.open(working_file) metadata.add_metadata(working_file, {'Artist': artist, 'Software': software}) output_path = os.path.splitext(working_file)[0] + '_watermarked.png' image.save(output_path, format='PNG') output_entry.set(output_path) #数字签名 if signature_check.get(): output_path = os.path.splitext(working_file)[0]+ '.pctf' key = signature.generate_key_from_string(signature_key_entry.get()) signature.generate_signature(working_file, key, output_path) #报错输出 except Exception as e: messagebox.showerror("错误", f"在处理水印时发生错误:{e}") return messagebox.showinfo("完成", "水印处理完成。") def upload_to_ipfs(): file_path = file_entry.get() if file_path: result = ipfs.upload_to_ipfs(file_path) # 假设这是您提供的函数 if result.get('ok') and 'value' in result and 'cid' in result['value']: cid = result['value']['cid'] ipfs_cid.set(f"IPFS CID: {cid}") ipfs_url.set(f"IPFS链接: https://ipfs.io/ipfs/{cid}") else: ipfs_cid.set("上传失败或无效的返回值") ipfs_url.set("") else: messagebox.showinfo("提示", "没有选择有效的文件。") def extract_watermark_and_metadata(): file_path = get_working_file() if file_path: blind_key = blind_key_entry.get() wm_length = int(blind_key) extracted_wm = blind.extract_watermark(file_path, wm_length) extracted_metadata = metadata.read_metadata(file_path) watermark_result.set(f"提取出的水印: {extracted_wm}") metadata_result.set(f"元数据: {extracted_metadata}") else: messagebox.showinfo("提示", "没有选择有效的文件。") def verify_signature(): signature_file = filedialog.askopenfilename(filetypes=[("PCTF Files", "*.pctf")]) if signature_file: picture_path = get_working_file() key = verify_key_entry result = signature.verify_signature(picture_path,key,signature_file) signature_result.set("验证成功" if result else "验证失败") else: messagebox.showinfo("提示", "没有选择有效的数字签名文件。") proxy_url = 'http://node.invisomark.keyfox.xyz/serpapi_search.php' def fetch_and_display_sources(api_key, image_url, display_window): try: page_token = tracepicture.fetch_google_lens_page_token(api_key, image_url) image_sources_results = tracepicture.fetch_google_lens_image_sources(api_key, page_token) for source in image_sources_results['image_sources']: source_frame = tk.Frame(display_window) source_frame.pack(fill='x', expand=True) logo = ImageTk.PhotoImage(Image.open(requests.get(source['source_logo'], stream=True).raw)) logo_label = tk.Label(source_frame, image=logo) logo_label.image = logo logo_label.pack(side='left') source_label = tk.Label(source_frame, text=source['source']) source_label.pack(side='left') link_button = tk.Button(source_frame, text="打开链接", command=lambda url=source['link']: webbrowser.open(url)) link_button.pack(side='left') except Exception as e: messagebox.showerror("错误", f"报错: {e}") def fetch_and_display_sources_proxy(api_key, image_url, display_window): response = requests.post(proxy_url, data={'api_key': api_key, 'image_url': image_url}) response_text = response.text sources = re.findall(r"\[source\] => (.+?)\n", response_text) source_logos = re.findall(r"\[source_logo\] => (.+?)\n", response_text) links = re.findall(r"\[link\] => (.+?)\n", response_text) for source, source_logo, link in zip(sources, source_logos, links): source_frame = tk.Frame(display_window) source_frame.pack(fill='x', expand=True) # 显示 source logo logo_response = requests.get(source_logo) logo_image = Image.open(io.BytesIO(logo_response.content)) logo_photo = ImageTk.PhotoImage(logo_image) logo_label = tk.Label(source_frame, image=logo_photo) logo_label.image = logo_photo # 保持对图像的引用 logo_label.pack(side='left') # 显示 source source_label = tk.Label(source_frame, text=source) source_label.pack(side='left') # 显示 link link_button = tk.Button(source_frame, text="打开链接", command=lambda l=link: webbrowser.open(l)) link_button.pack(side='left') def trace_image(): api_key = api_key_entry.get() image_url = image_url_entry.get() if not api_key: messagebox.showinfo("提示", "请输入 API 密钥。") return if not image_url: messagebox.showinfo("提示", "请输入图片链接。") return try: display_window = tk.Toplevel(app) display_window.title("图片回溯结果") display_window.geometry("600x400") scrollable_frame = tk.Frame(display_window) scrollable_canvas = tk.Canvas(scrollable_frame) scrollbar = tk.Scrollbar(scrollable_frame, orient="vertical", command=scrollable_canvas.yview) scrollable_frame.pack(fill='both', expand=True) scrollable_canvas.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") scrollable_canvas.configure(yscrollcommand=scrollbar.set) scrollable_canvas.bind('<Configure>', lambda e: scrollable_canvas.configure(scrollregion=scrollable_canvas.bbox('all'))) if use_proxy.get(): fetch_and_display_sources_proxy(api_key, image_url, scrollable_canvas) else: fetch_and_display_sources(api_key, image_url, scrollable_canvas) except Exception as e: messagebox.showerror("错误", f"报错: {e}") def show_developer_info(): developer_info = "开发者信息:\n开发者:键狐 \n Github: https://github.com/jianhuxwx/invisomark/ \n本项目为免费开源项目,如果付费购买该软件,请立即退款!" messagebox.showinfo("开发者信息", developer_info) app = ctk.CTk() app.geometry("400x600") app.title("INVISOMARK 键狐制作") left_frame = ctk.CTkFrame(app, width=200, height=600) left_frame.pack(side="left", fill="both", expand=True) right_frame = ctk.CTkFrame(app, width=200, height=600) right_frame.pack(side="right", fill="both", expand=True) image_label = ctk.CTkLabel(left_frame, text="图片预览") image_label.pack(pady=10) file_entry = ctk.StringVar(app) output_entry = ctk.StringVar(app) choose_file_button = ctk.CTkButton(right_frame, text="选择文件", command=choose_file, width=150, height=25) choose_file_button.pack(pady=5) file_label = ctk.CTkLabel(right_frame, textvariable=file_entry) file_label.pack(pady=5) output_label = ctk.CTkLabel(right_frame, textvariable=output_entry) output_label.pack(pady=5) # 盲水印面板 blind_watermark_pane = CollapsiblePane(right_frame, title="盲水印") blind_watermark_pane.pack(fill="x", pady=2) blind_watermark_check = ctk.CTkCheckBox(blind_watermark_pane.content_frame, text="启用盲水印") blind_watermark_pane.add_widget(blind_watermark_check) watermark_text_entry = ctk.CTkEntry(blind_watermark_pane.content_frame, placeholder_text="水印文本") blind_watermark_pane.add_widget(watermark_text_entry) blind_key_label = ctk.StringVar(app) blind_key_display = ctk.CTkLabel(blind_watermark_pane.content_frame, textvariable=blind_key_label) blind_watermark_pane.add_widget(blind_key_display) # 线性水印面板 line_watermark_pane = CollapsiblePane(right_frame, title="线性水印") line_watermark_pane.pack(fill="x", pady=2) line_watermark_check = ctk.CTkCheckBox(line_watermark_pane.content_frame, text="启用线性水印") line_watermark_pane.add_widget(line_watermark_check) line_text_entry = ctk.CTkEntry(line_watermark_pane.content_frame, placeholder_text="线条水印文本") line_watermark_pane.add_widget(line_text_entry) font_size_entry = ctk.CTkEntry(line_watermark_pane.content_frame, placeholder_text="字体大小") line_watermark_pane.add_widget(font_size_entry) red_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=255, command=update_sliders) line_watermark_pane.add_widget(red_slider) green_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=255, command=update_sliders) line_watermark_pane.add_widget(green_slider) blue_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=255, command=update_sliders) line_watermark_pane.add_widget(blue_slider) alpha_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=10, command=update_sliders) line_watermark_pane.add_widget(alpha_slider) red_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0") line_watermark_pane.add_widget(red_value_label) green_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0") line_watermark_pane.add_widget(green_value_label) blue_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0") line_watermark_pane.add_widget(blue_value_label) alpha_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0.0") line_watermark_pane.add_widget(alpha_value_label) # 全屏水印面板 full_watermark_pane = CollapsiblePane(right_frame, title="全屏水印") full_watermark_pane.pack(fill="x", pady=2) full_watermark_check = ctk.CTkCheckBox(full_watermark_pane.content_frame, text="启用全屏水印") full_watermark_pane.add_widget(full_watermark_check) full_watermark_text_entry = ctk.CTkEntry(full_watermark_pane.content_frame, placeholder_text="全屏水印文本") full_watermark_pane.add_widget(full_watermark_text_entry) # 基本水印面板 basic_watermark_pane = CollapsiblePane(right_frame, title="基本水印") basic_watermark_pane.pack(fill="x", pady=2) basic_watermark_check = ctk.CTkCheckBox(basic_watermark_pane.content_frame, text="启用基本水印") basic_watermark_pane.add_widget(basic_watermark_check) # 模糊水印面板 blur_watermark_pane = CollapsiblePane(right_frame, title="模糊水印") blur_watermark_pane.pack(fill="x", pady=2) blur_watermark_check = ctk.CTkCheckBox(blur_watermark_pane.content_frame, text="启用模糊水印") blur_watermark_pane.add_widget(blur_watermark_check) blur_level_entry = ctk.CTkEntry(blur_watermark_pane.content_frame, placeholder_text="模糊度") blur_watermark_pane.add_widget(blur_level_entry) # 元数据面板 metadata_pane = CollapsiblePane(right_frame, title="元数据") metadata_pane.pack(fill="x", pady=2) metadata_check = ctk.CTkCheckBox(metadata_pane.content_frame, text="启用元数据") metadata_pane.add_widget(metadata_check) artist_entry = ctk.CTkEntry(metadata_pane.content_frame, placeholder_text="艺术家名称") metadata_pane.add_widget(artist_entry) software_entry = ctk.CTkEntry(metadata_pane.content_frame, placeholder_text="软件名称") metadata_pane.add_widget(software_entry) # 数字签名面板 signature_pane = CollapsiblePane(right_frame, title="数字签名") signature_pane.pack(fill="x", pady=2) signature_check = ctk.CTkCheckBox(signature_pane.content_frame, text="启用数字签名") signature_pane.add_widget(signature_check) signature_key_entry = ctk.CTkEntry(signature_pane.content_frame, placeholder_text="数字签名密钥") signature_pane.add_widget(signature_key_entry) # 验证面板 verification_pane = CollapsiblePane(right_frame, title="验证") verification_pane.pack(fill="x", pady=2) ipfs_cid = ctk.StringVar(app) ipfs_url = ctk.StringVar(app) watermark_result = ctk.StringVar(app) metadata_result = ctk.StringVar(app) signature_result = ctk.StringVar(app) upload_to_ipfs_button = ctk.CTkButton(verification_pane.content_frame, text="上传到IPFS", command=upload_to_ipfs, width=150, height=25) upload_to_ipfs_button.pack(pady=5) # 在 UI 中添加复制 CID 的按钮 copy_cid_button = ctk.CTkButton(verification_pane.content_frame, text="复制 CID", command=lambda: copy_to_clipboard(ipfs_cid.get())) copy_cid_button.pack(pady=5) ipfs_cid_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=ipfs_cid) # 在 UI 中添加复制 CID 链接的按钮 copy_cid_url_button = ctk.CTkButton(verification_pane.content_frame, text="复制 CID 链接", command=lambda: copy_to_clipboard(ipfs_url.get())) copy_cid_url_button.pack(pady=5) ipfs_cid_label.pack(pady=5) ipfs_url_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=ipfs_url) ipfs_url_label.pack(pady=5) blind_key_entry = ctk.CTkEntry(verification_pane.content_frame, placeholder_text="请输入盲水印密钥") blind_key_entry.pack(pady=5) extract_wm_button = ctk.CTkButton(verification_pane.content_frame, text="解读水印和元数据", command=extract_watermark_and_metadata, width=150, height=25) extract_wm_button.pack(pady=5) watermark_result_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=watermark_result) watermark_result_label.pack(pady=5) metadata_result_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=metadata_result) metadata_result_label.pack(pady=5) verify_key_entry = ctk.CTkEntry(verification_pane.content_frame, placeholder_text="请输入验证密钥") verify_key_entry.pack(pady=5) verify_signature_button = ctk.CTkButton(verification_pane.content_frame, text="验证数字签名", command=verify_signature, width=150, height=25) verify_signature_button.pack(pady=5) signature_result_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=signature_result) signature_result_label.pack(pady=5) # 图片溯源面板 trace_pane = CollapsiblePane(right_frame, title="图片溯源") use_proxy = tk.BooleanVar(value=False) proxy_checkbutton = ctk.CTkCheckBox(trace_pane.content_frame, text="使用代理服务器", variable=use_proxy) proxy_checkbutton.pack(pady=5) trace_pane.pack(fill="x", pady=2) api_key_entry = ctk.CTkEntry(trace_pane.content_frame, placeholder_text="请输入您的API密钥") api_key_entry.pack(pady=5) image_url_entry = ctk.CTkEntry(trace_pane.content_frame, placeholder_text="输入图片链接") image_url_entry.pack(pady=5) trace_button = ctk.CTkButton(trace_pane.content_frame, text="图片溯源", command=trace_image) trace_button.pack(pady=5) developer_info_button = ctk.CTkButton(left_frame, text="显示开发者信息", command=show_developer_info) developer_info_button.pack(pady=5) # 应用水印面板 apply_watermarks_button = ctk.CTkButton(right_frame, text="应用水印", command=apply_watermarks, width=150, height=25) apply_watermarks_button.pack(pady=10) app.mainloop()
20,299
Python
.py
397
42.670025
145
0.712808
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,370
main_en.py
jianhuxwx_invisomark/main_en.py
''' <INVISOMARK - Greatest Watermark Software> Copyright (C) <2023> <YuexuChen> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. ''' import customtkinter as ctk import tkinter.filedialog as filedialog import tkinter.messagebox as messagebox from PIL import Image, ImageTk import os import basic_watermark import full_watermark import line import metadata import signature import blind import blur import ipfs import webbrowser import tracepicture import tkinter as tk import tkinter.scrolledtext as scrolledtext import requests import re import io class CollapsiblePane(ctk.CTkFrame): def __init__(self, parent, title="", *args, **kwargs): super().__init__(parent, *args, **kwargs) self.title = title self.toggle_button = ctk.CTkButton(self, text=self.title, command=self.toggle) self.toggle_button.pack(fill="x", pady=2) self.content_frame = ctk.CTkFrame(self) self.content_visible = False def toggle(self): if self.content_visible: self.content_frame.pack_forget() self.content_visible = False else: self.content_frame.pack(fill="x", expand=True) self.content_visible = True def add_widget(self, widget): widget.pack(fill="x", pady=2) # Necessary method definitions def copy_to_clipboard(text): app.clipboard_clear() app.clipboard_append(text) messagebox.showinfo("Copy succeeded", "Copied to clipboard") # Update sliders def update_sliders(event=None): red_value_label.configure(text="Red:"+f"{red_slider.get():.0f}") green_value_label.configure(text="Green:"+f"{green_slider.get():.0f}") blue_value_label.configure(text="Blue:"+f"{blue_slider.get():.0f}") alpha_value_label.configure(text="Transparency:"+f"{alpha_slider.get() / 10:.1f}") # Select file def choose_file(): file_path = filedialog.askopenfilename() if file_path: file_entry.set(file_path) update_output_path(file_path) update_image_preview(file_path) else: file_entry.set('') output_entry.set('') # Update output file path def update_output_path(input_path): base, ext = os.path.splitext(input_path) output_path = base + '_watermarked.png' output_entry.set(output_path) # Update instance def update_image_preview(file_path): try: img = Image.open(file_path) img.thumbnail((200, 200)) img = ImageTk.PhotoImage(img) image_label.configure(image=img) image_label.image = img except Exception as e: image_label.configure(image='') image_label.text = 'Image preview unavailable' # Get picture path def get_working_file(): original = file_entry.get() watermarked = output_entry.get() if os.path.exists(original) or os.path.exists(watermarked): return watermarked if os.path.exists(watermarked) else original else: return None # Apply watermarks def apply_watermarks(): working_file = get_working_file() if not working_file: messagebox.showinfo("Tip", "No valid file selected.") return output_file = output_entry.get() try: # Blind watermark if blind_watermark_check.get(): watermark_text = watermark_text_entry.get() blind_result = blind.embed_watermark(working_file, watermark_text, output_file) if isinstance(blind_result, tuple): blind_key = blind_result[0] blind_key_label.set(f"Blind watermark key (keep it safe): {blind_key}") else: blind_key_label.set(f"Blind watermark key (keep it safe): {blind_result}") working_file = output_file # Linear watermark if line_watermark_check.get(): input_text = line_text_entry.get() font_size = int(font_size_entry.get()) red = int(red_slider.get()) green = int(green_slider.get()) blue = int(blue_slider.get()) alpha = alpha_slider.get() / 10 font_color = (red, green, blue, int(alpha * 255)) line.write_text_along_path(working_file, input_text, output_file, font_size=font_size, font_color=font_color) # Full screen watermark if full_watermark_check.get(): full_watermark_text = full_watermark_text_entry.get() full_watermark.add_watermark(working_file, output_file, full_watermark_text) # Basic watermark if basic_watermark_check.get(): basic_watermark_text = watermark_text_entry.get() basic_watermark.add_watermark(working_file, output_file, basic_watermark_text) # Blur picture if blur_watermark_check.get(): blur_level = int(blur_level_entry.get()) blur.blur_image(working_file, output_file, blur_level) # Metadata if metadata_check.get(): artist = artist_entry.get() software = software_entry.get() image = Image.open(working_file) metadata.add_metadata(working_file, {'Artist': artist, 'Software': software}) output_path = os.path.splitext(working_file)[0] + '_watermarked.png' image.save(output_path, format='PNG') output_entry.set(output_path) # Digital signature if signature_check.get(): output_path = os.path.splitext(working_file)[0]+ '.pctf' key = signature.generate_key_from_string(signature_key_entry.get()) signature.generate_signature(working_file, key, output_path) # Error output except Exception as e: messagebox.showerror("Error", f"Error processing watermark: {e}") return messagebox.showinfo("Completed", "Watermark processing completed.") def upload_to_ipfs(): file_path = file_entry.get() if file_path: result = ipfs.upload_to_ipfs(file_path) # if result.get('ok') and 'value' in result and 'cid' in result['value']: cid = result['value']['cid'] ipfs_cid.set(f"IPFS CID: {cid}") ipfs_url.set(f"IPFS link: https://ipfs.io/ipfs/{cid}") else: ipfs_cid.set("Upload failed or invalid return value") ipfs_url.set("") else: messagebox.showinfo("Tip", "No valid file selected.") def extract_watermark_and_metadata(): file_path = get_working_file() if file_path: blind_key = blind_key_entry.get() wm_length = int(blind_key) extracted_wm = blind.extract_watermark(file_path, wm_length) extracted_metadata = metadata.read_metadata(file_path) watermark_result.set(f"Extracted watermark: {extracted_wm}") metadata_result.set(f"Metadata: {extracted_metadata}") else: messagebox.showinfo("Tip", "No valid file selected.") def verify_signature(): signature_file = filedialog.askopenfilename(filetypes=[("PCTF Files", "*.pctf")]) if signature_file: picture_path = get_working_file() key = verify_key_entry result = signature.verify_signature(picture_path,key,signature_file) signature_result.set("Verification succeeded" if result else "Verification failed") else: messagebox.showinfo("Tip", "No valid digital signature file selected.") proxy_url = 'http://node.invisomark.keyfox.xyz/serpapi_search.php' def fetch_and_display_sources(api_key, image_url, display_window): try: page_token = tracepicture.fetch_google_lens_page_token(api_key, image_url) image_sources_results = tracepicture.fetch_google_lens_image_sources(api_key, page_token) for source in image_sources_results['image_sources']: source_frame = tk.Frame(display_window) source_frame.pack(fill='x', expand=True) logo = ImageTk.PhotoImage(Image.open(requests.get(source['source_logo'], stream=True).raw)) logo_label = tk.Label(source_frame, image=logo) logo_label.image = logo logo_label.pack(side='left') source_label = tk.Label(source_frame, text=source['source']) source_label.pack(side='left') link_button = tk.Button(source_frame, text="Open link", command=lambda url=source['link']: webbrowser.open(url)) link_button.pack(side='left') except Exception as e: messagebox.showerror("Error", f"Error: {e}") def fetch_and_display_sources_proxy(api_key, image_url, display_window): response = requests.post(proxy_url, data={'api_key': api_key, 'image_url': image_url}) response_text = response.text sources = re.findall(r"\[source\] => (.+?)\n", response_text) source_logos = re.findall(r"\[source_logo\] => (.+?)\n", response_text) links = re.findall(r"\[link\] => (.+?)\n", response_text) for source, source_logo, link in zip(sources, source_logos, links): source_frame = tk.Frame(display_window) source_frame.pack(fill='x', expand=True) # Display source logo logo_response = requests.get(source_logo) logo_image = Image.open(io.BytesIO(logo_response.content)) logo_photo = ImageTk.PhotoImage(logo_image) logo_label = tk.Label(source_frame, image=logo_photo) logo_label.image = logo_photo # Keep reference to image logo_label.pack(side='left') # Display source source_label = tk.Label(source_frame, text=source) source_label.pack(side='left') # Display link link_button = tk.Button(source_frame, text="Open link", command=lambda l=link: webbrowser.open(l)) link_button.pack(side='left') def trace_image(): api_key = api_key_entry.get() image_url = image_url_entry.get() if not api_key: messagebox.showinfo("Tip", "Please enter API key.") return if not image_url: messagebox.showinfo("Tip", "Please enter image link.") return try: display_window = tk.Toplevel(app) display_window.title("Image trace result") display_window.geometry("600x400") scrollable_frame = tk.Frame(display_window) scrollable_canvas = tk.Canvas(scrollable_frame) scrollbar = tk.Scrollbar(scrollable_frame, orient="vertical", command=scrollable_canvas.yview) scrollable_frame.pack(fill='both', expand=True) scrollable_canvas.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") scrollable_canvas.configure(yscrollcommand=scrollbar.set) scrollable_canvas.bind('<Configure>', lambda e: scrollable_canvas.configure(scrollregion=scrollable_canvas.bbox('all'))) if use_proxy.get(): fetch_and_display_sources_proxy(api_key, image_url, scrollable_canvas) else: fetch_and_display_sources(api_key, image_url, scrollable_canvas) except Exception as e: messagebox.showerror("Error", f"Error: {e}") def show_developer_info(): developer_info = "Developer information:\nDeveloper: Keyfox \n Github: https://github.com/jianhuxwx/invisomark/ \nThis project is a free open source project. If you paid to purchase this software, please get a refund immediately!" messagebox.showinfo("Developer information", developer_info) app = ctk.CTk() app.geometry("400x600") app.title("INVISOMARK by Keyfox") left_frame = ctk.CTkFrame(app, width=200, height=600) left_frame.pack(side="left", fill="both", expand=True) right_frame = ctk.CTkFrame(app, width=200, height=600) right_frame.pack(side="right", fill="both", expand=True) image_label = ctk.CTkLabel(left_frame, text="Image preview") image_label.pack(pady=10) file_entry = ctk.StringVar(app) output_entry = ctk.StringVar(app) choose_file_button = ctk.CTkButton(right_frame, text="Select file", command=choose_file, width=150, height=25) choose_file_button.pack(pady=5) file_label = ctk.CTkLabel(right_frame, textvariable=file_entry) file_label.pack(pady=5) output_label = ctk.CTkLabel(right_frame, textvariable=output_entry) output_label.pack(pady=5) # Blind watermark panel blind_watermark_pane = CollapsiblePane(right_frame, title="Blind watermark") blind_watermark_pane.pack(fill="x", pady=2) blind_watermark_check = ctk.CTkCheckBox(blind_watermark_pane.content_frame, text="Enable blind watermark") blind_watermark_pane.add_widget(blind_watermark_check) watermark_text_entry = ctk.CTkEntry(blind_watermark_pane.content_frame, placeholder_text="Watermark text") blind_watermark_pane.add_widget(watermark_text_entry) blind_key_label = ctk.StringVar(app) blind_key_display = ctk.CTkLabel(blind_watermark_pane.content_frame, textvariable=blind_key_label) blind_watermark_pane.add_widget(blind_key_display) # Linear watermark panel line_watermark_pane = CollapsiblePane(right_frame, title="Linear watermark") line_watermark_pane.pack(fill="x", pady=2) line_watermark_check = ctk.CTkCheckBox(line_watermark_pane.content_frame, text="Enable linear watermark") line_watermark_pane.add_widget(line_watermark_check) line_text_entry = ctk.CTkEntry(line_watermark_pane.content_frame, placeholder_text="Text for line watermark") line_watermark_pane.add_widget(line_text_entry) font_size_entry = ctk.CTkEntry(line_watermark_pane.content_frame, placeholder_text="Font size") line_watermark_pane.add_widget(font_size_entry) red_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=255, command=update_sliders) line_watermark_pane.add_widget(red_slider) green_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=255, command=update_sliders) line_watermark_pane.add_widget(green_slider) blue_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=255, command=update_sliders) line_watermark_pane.add_widget(blue_slider) alpha_slider = ctk.CTkSlider(line_watermark_pane.content_frame, from_=0, to=10, command=update_sliders) line_watermark_pane.add_widget(alpha_slider) red_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0") line_watermark_pane.add_widget(red_value_label) green_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0") line_watermark_pane.add_widget(green_value_label) blue_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0") line_watermark_pane.add_widget(blue_value_label) alpha_value_label = ctk.CTkLabel(line_watermark_pane.content_frame, text="0.0") line_watermark_pane.add_widget(alpha_value_label) # Full screen watermark panel full_watermark_pane = CollapsiblePane(right_frame, title="Full screen watermark") full_watermark_pane.pack(fill="x", pady=2) full_watermark_check = ctk.CTkCheckBox(full_watermark_pane.content_frame, text="Enable full screen watermark") full_watermark_pane.add_widget(full_watermark_check) full_watermark_text_entry = ctk.CTkEntry(full_watermark_pane.content_frame, placeholder_text="Full screen watermark text") full_watermark_pane.add_widget(full_watermark_text_entry) # Basic watermark panel basic_watermark_pane = CollapsiblePane(right_frame, title="Basic watermark") basic_watermark_pane.pack(fill="x", pady=2) basic_watermark_check = ctk.CTkCheckBox(basic_watermark_pane.content_frame, text="Enable basic watermark") basic_watermark_pane.add_widget(basic_watermark_check) # Blur watermark panel blur_watermark_pane = CollapsiblePane(right_frame, title="Blur watermark") blur_watermark_pane.pack(fill="x", pady=2) blur_watermark_check = ctk.CTkCheckBox(blur_watermark_pane.content_frame, text="Enable blur watermark") blur_watermark_pane.add_widget(blur_watermark_check) blur_level_entry = ctk.CTkEntry(blur_watermark_pane.content_frame, placeholder_text="Blur level") blur_watermark_pane.add_widget(blur_level_entry) # Metadata panel metadata_pane = CollapsiblePane(right_frame, title="Metadata") metadata_pane.pack(fill="x", pady=2) metadata_check = ctk.CTkCheckBox(metadata_pane.content_frame, text="Enable metadata") metadata_pane.add_widget(metadata_check) artist_entry = ctk.CTkEntry(metadata_pane.content_frame, placeholder_text="Artist name") metadata_pane.add_widget(artist_entry) software_entry = ctk.CTkEntry(metadata_pane.content_frame, placeholder_text="Software name") metadata_pane.add_widget(software_entry) # Digital signature panel signature_pane = CollapsiblePane(right_frame, title="Digital signature") signature_pane.pack(fill="x", pady=2) signature_check = ctk.CTkCheckBox(signature_pane.content_frame, text="Enable digital signature") signature_pane.add_widget(signature_check) signature_key_entry = ctk.CTkEntry(signature_pane.content_frame, placeholder_text="Digital signature key") signature_pane.add_widget(signature_key_entry) # Verification panel verification_pane = CollapsiblePane(right_frame, title="Verification") verification_pane.pack(fill="x", pady=2) ipfs_cid = ctk.StringVar(app) ipfs_url = ctk.StringVar(app) watermark_result = ctk.StringVar(app) metadata_result = ctk.StringVar(app) signature_result = ctk.StringVar(app) upload_to_ipfs_button = ctk.CTkButton(verification_pane.content_frame, text="Upload to IPFS", command=upload_to_ipfs, width=150, height=25) upload_to_ipfs_button.pack(pady=5) # Add button to copy CID in UI copy_cid_button = ctk.CTkButton(verification_pane.content_frame, text="Copy CID", command=lambda: copy_to_clipboard(ipfs_cid.get())) copy_cid_button.pack(pady=5) ipfs_cid_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=ipfs_cid) # Add button to copy CID link in UI copy_cid_url_button = ctk.CTkButton(verification_pane.content_frame, text="Copy CID link", command=lambda: copy_to_clipboard(ipfs_url.get())) copy_cid_url_button.pack(pady=5) ipfs_cid_label.pack(pady=5) ipfs_url_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=ipfs_url) ipfs_url_label.pack(pady=5) blind_key_entry = ctk.CTkEntry(verification_pane.content_frame, placeholder_text="Please enter blind watermark key") blind_key_entry.pack(pady=5) extract_wm_button = ctk.CTkButton(verification_pane.content_frame, text="Extract watermark and metadata", command=extract_watermark_and_metadata, width=150, height=25) extract_wm_button.pack(pady=5) watermark_result_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=watermark_result) watermark_result_label.pack(pady=5) metadata_result_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=metadata_result) metadata_result_label.pack(pady=5) verify_key_entry = ctk.CTkEntry(verification_pane.content_frame, placeholder_text="Please enter verification key") verify_key_entry.pack(pady=5) verify_signature_button = ctk.CTkButton(verification_pane.content_frame, text="Verify digital signature", command=verify_signature, width=150, height=25) verify_signature_button.pack(pady=5) signature_result_label = ctk.CTkLabel(verification_pane.content_frame, textvariable=signature_result) signature_result_label.pack(pady=5) # Image trace panel trace_pane = CollapsiblePane(right_frame, title="Image trace") use_proxy = tk.BooleanVar(value=False) proxy_checkbutton = ctk.CTkCheckBox(trace_pane.content_frame, text="Use proxy server", variable=use_proxy) proxy_checkbutton.pack(pady=5) trace_pane.pack(fill="x", pady=2) api_key_entry = ctk.CTkEntry(trace_pane.content_frame, placeholder_text="Please enter your API key") api_key_entry.pack(pady=5) image_url_entry = ctk.CTkEntry(trace_pane.content_frame, placeholder_text="Enter image link") image_url_entry.pack(pady=5) trace_button = ctk.CTkButton(trace_pane.content_frame, text="Image trace", command=trace_image) trace_button.pack(pady=5) developer_info_button = ctk.CTkButton(left_frame, text="Show developer info", command=show_developer_info) developer_info_button.pack(pady=5) # Apply watermarks panel apply_watermarks_button = ctk.CTkButton(right_frame, text="Apply watermarks", command=apply_watermarks, width=150, height=25) apply_watermarks_button.pack(pady=10) app.mainloop()
20,853
Python
.py
397
46.080605
234
0.714865
jianhuxwx/invisomark
8
0
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,371
_copySymbols.js
gmkung_Cheemera/node_modules/lodash/_copySymbols.js
var copyObject = require('./_copyObject'), getSymbols = require('./_getSymbols'); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols;
446
Python
.py
14
29.785714
61
0.709302
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,372
_copyArray.js
gmkung_Cheemera/node_modules/lodash/_copyArray.js
/** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray;
454
Python
.py
18
22.611111
57
0.654378
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,373
_copySymbolsIn.js
gmkung_Cheemera/node_modules/lodash/_copySymbolsIn.js
var copyObject = require('./_copyObject'), getSymbolsIn = require('./_getSymbolsIn'); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn;
470
Python
.py
14
31.5
61
0.720264
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,374
_copyObject.js
gmkung_Cheemera/node_modules/lodash/_copyObject.js
var assignValue = require('./_assignValue'), baseAssignValue = require('./_baseAssignValue'); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject;
1,044
Python
.py
34
26.911765
74
0.665339
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,375
test.py
gmkung_Cheemera/python/test.py
import json from typing import NamedTuple, List from Cheemera import * # Function to create Property instances def create_property(data): return Property(valence=data['valence'], sentence=data['sentence']) # Function to create Consequence instances def create_consequence(data): return Consequence(modal=data['modal'], properties=[create_property(p) for p in data['properties']]) # Function to create Scenario instances def create_scenario(data): return Scenario( type=data['type'], consequences=[create_consequence(c) for c in data['consequences']], antecedents=[[create_property(p) for p in antecedent] for antecedent in data['antecedents']] ) # Function to create Belief instances def create_belief(data): return Belief( beliefUniqueId=data['beliefUniqueId'], originatingRuleSystemName=data['originatingRuleSystemName'], originatingRuleSystemUuid=data['originatingRuleSystemUuid'], scenario=create_scenario(data['scenario']) ) # JSON data as a string json_data = ''' { "beliefSet": { "beliefs": [ { "beliefUniqueId": "1", "originatingRuleSystemName": "UserQuery", "originatingRuleSystemUuid": "1", "scenario": { "type": "IF_THEN", "consequences": [ { "modal": "Always", "properties": [ { "valence": true, "sentence": "D is true" }, { "valence": true, "sentence": "E is true" } ] } ], "antecedents": [ [ { "valence": true, "sentence": "A is true" }, { "valence": true, "sentence": "B is true" } ], [ { "valence": true, "sentence": "C is true" } ] ] } }, { "beliefUniqueId": "2", "originatingRuleSystemName": "UserQuery", "originatingRuleSystemUuid": "2", "scenario": { "type": "MUTUAL_EXCLUSION", "consequences": [ { "modal": "Always", "properties": [ { "valence": true, "sentence": "G is true" } ] }, { "modal": "Never", "properties": [ { "valence": true, "sentence": "H is true" } ] } ], "antecedents": [ [ { "valence": true, "sentence": "L is true" }], [{ "valence": true, "sentence": "F is true" } ] ] } }, { "beliefUniqueId": "3", "originatingRuleSystemName": "UserQuery", "originatingRuleSystemUuid": "3", "scenario": { "type": "IF_THEN", "consequences": [ { "modal": "Never", "properties": [ { "valence": true, "sentence": "A is true" }, { "valence": true, "sentence": "F is true" } ] } ], "antecedents": [ [ { "valence": true, "sentence": "B is true" }, { "valence": true, "sentence": "H is true" } ] ] } } ], "beliefSetName": "UserQueryInference", "beliefSetOwner": "Cheemera", "beliefSetVersion": "1.0" }, "explore": [ { "valence": true, "sentence": "C is true" }, { "valence": true, "sentence": "H is true" } ] } ''' # Parse the JSON data parsed_data = json.loads(json_data) # Create the BeliefSet instance belief_set_data = parsed_data['beliefSet'] belief_set = BeliefSet( beliefs=[create_belief(belief) for belief in belief_set_data['beliefs']], beliefSetName=belief_set_data['beliefSetName'], beliefSetOwner=belief_set_data['beliefSetOwner'], beliefSetVersion=belief_set_data['beliefSetVersion'], blindReferenceExternalIdArray='123123123' ) # Create the explore list explore = [create_property(p) for p in parsed_data['explore']] print (explore_belief_set({"explore": explore, "beliefSet": belief_set})) # Now, 'belief_set' and 'explore' can be used as input for your exploreBeliefSet function
4,882
Python
.py
177
17.135593
104
0.471353
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,376
Cheemera.py
gmkung_Cheemera/python/Cheemera.py
from typing import NamedTuple, List, Optional, Any, Dict,Set import json import hashlib def explore_belief_set(request_body: Dict[str, Any]): try: explore = request_body['explore'] belief_set = request_body['beliefSet'] # Normalise to 'LET' scenarios normalised_belief_set = normalise_belief_set(belief_set) # Create assertions assertion_set = generate_assertions(normalised_belief_set) # Explore assertions using 'explore' explore_results = explore_assertions(explore, assertion_set) return explore_results except Exception as error: # Simulate a 500 response return f"An error occurred while processing the request: {error}" # Define Python equivalent classes for TypeScript interfaces class Property(NamedTuple): valence: bool sentence: str class Consequence(NamedTuple): modal: str # ModalType in TypeScript properties: List[Property] class Scenario(NamedTuple): type: str # ScenarioType in TypeScript consequences: List[Consequence] antecedents: List[List[Property]] class Belief(NamedTuple): scenario: Scenario beliefUniqueId: str originatingRuleSystemName: str originatingRuleSystemUuid: str class BeliefSet(NamedTuple): beliefs: List[Belief] beliefSetName: str beliefSetOwner: str beliefSetVersion: str blindReferenceExternalIdArray: List[Any] class Assertion(NamedTuple): exclude: bool properties: List[Property] sourceBeliefId: Optional[str] = None class AssertionSet(NamedTuple): assertions: List[Assertion] class ReasoningStep(NamedTuple): inferenceStepType: str sourceBeliefId: Optional[str] = None deducedProperty: Optional[List[Property]] = None class ExploreResult(NamedTuple): resultCode: str resultReason: str results: Dict[str, Any] # Assume the invertValences function has been ported over to Python as well def invert_valences(properties: List[Property]) -> List[Property]: # Implement the logic to invert valences pass # Helper functions def is_assertion_excluded(assertion: Assertion, explore_obj: List[Property]) -> bool: return assertion.exclude and all( any(obj.sentence == prop.sentence and obj.valence == prop.valence for obj in explore_obj) for prop in assertion.properties ) def calculate_residue(assertion: Assertion, explore_obj: List[Property]) -> List[Property]: return [prop for prop in assertion.properties if not any( obj.sentence == prop.sentence and obj.valence == prop.valence for obj in explore_obj )] def is_new_property(property: Property, explore_obj: List[Property]) -> bool: return all(obj.sentence != property.sentence for obj in explore_obj) def calculate_secondary_residues(residue: List[Property], explore_obj: List[Property]) -> List[str]: return [obj.sentence for obj in residue if not any( obj.sentence == sentence for sentence in explore_obj )] # Main function def explore_assertions(explore: List[Property], assertion_set: AssertionSet) -> ExploreResult: discoveries = explore.copy() result_obj = ExploreResult( resultCode="Success", resultReason="Successful with no errors found", results={ "possible": True, "reasoningSteps": [], "arrayOfSecondaryResidues": [], } ) turn = 1 previous_md5 = None while hashlib.md5(json.dumps(discoveries, sort_keys=True).encode()).hexdigest() != previous_md5 or turn == 1: previous_md5 = hashlib.md5(json.dumps(discoveries, sort_keys=True).encode()).hexdigest() turn += 1 for assertion in assertion_set.assertions[:]: # Create a shallow copy to iterate over reasoning_step = ReasoningStep(inferenceStepType="Deductive") if is_assertion_excluded(assertion, discoveries): reasoning_step = reasoning_step._replace(sourceBeliefId=assertion.sourceBeliefId) result_obj.results['reasoningSteps'].append(reasoning_step) result_obj.results['possible'] = False return result_obj else: residue_obj = calculate_residue(assertion, discoveries) if len(residue_obj) == 1 and is_new_property(residue_obj[0], discoveries): deduced = invert_valences(residue_obj) reasoning_step = reasoning_step._replace(deducedProperty=deduced) reasoning_step = reasoning_step._replace(sourceBeliefId=assertion.sourceBeliefId) result_obj.results['reasoningSteps'].append(reasoning_step) discoveries.extend(deduced) assertion_set = AssertionSet(assertions=[a for a in assertion_set.assertions if a != assertion]) else: result_obj.results['arrayOfSecondaryResidues'].extend( calculate_secondary_residues(residue_obj, discoveries) ) return result_obj # Assuming Property, Belief, BeliefSet, Assertion, AssertionSet are already defined based on previous conversation # Helper functions to replace lodash functionalities def deduplicate_properties(properties: List[Property]) -> List[Property]: # Using a set comprehension to deduplicate based on a tuple of the property's attributes unique_properties = {prop.sentence: prop for prop in properties}.values() return list(unique_properties) def invert_valences(properties: List[Property]) -> List[Property]: return [Property(sentence=prop.sentence, valence=not prop.valence) for prop in properties] def create_always_assertions(filters: List[Property], adjectives: List[Property]) -> List[List[Property]]: return [[*filters, Property(sentence=adj.sentence, valence=not adj.valence)] for adj in adjectives] def breakdown_belief(compound_belief: Belief) -> List[Belief]: if compound_belief.scenario.type in ["MUTUAL_EXCLUSION", "MUTUAL_INCLUSION"]: modal_type = "Never" if compound_belief.scenario.type == "MUTUAL_EXCLUSION" else "Always" return [ Belief( scenario=Scenario( type="IF_THEN", consequences=[ Consequence(modal=modal_type, properties=fp) for j, fp in enumerate(compound_belief.scenario.antecedents) if i != j ], antecedents=[antecedent] ), beliefUniqueId=compound_belief.beliefUniqueId, originatingRuleSystemName=compound_belief.originatingRuleSystemName, originatingRuleSystemUuid=compound_belief.originatingRuleSystemUuid, ) for i, antecedent in enumerate(compound_belief.scenario.antecedents) ] else: return [compound_belief] def normalise_belief_set(belief_set: BeliefSet) -> BeliefSet: normalised_beliefs = [] for belief in belief_set.beliefs: if belief.scenario.type == "IF_THEN": normalised_beliefs.append(belief) elif belief.scenario.type in ["MUTUAL_EXCLUSION", "MUTUAL_INCLUSION"]: normalised_beliefs.extend(breakdown_belief(belief)) return BeliefSet( beliefs=normalised_beliefs, beliefSetName=belief_set.beliefSetName, beliefSetOwner=belief_set.beliefSetOwner, beliefSetVersion=belief_set.beliefSetVersion, blindReferenceExternalIdArray=belief_set.blindReferenceExternalIdArray, ) def generate_assertions(belief_set: BeliefSet) -> AssertionSet: assertions = [] for belief in belief_set.beliefs: if belief.scenario.type == "IF_THEN": for antecedent in belief.scenario.antecedents: for consequence in belief.scenario.consequences: if consequence.modal == "Always": to_exclude = create_always_assertions( antecedent, [prop for prop in consequence.properties if prop.sentence not in {fp.sentence for fp in antecedent}] ) for item in to_exclude: assertions.append(Assertion(exclude=True, properties=item, sourceBeliefId=belief.beliefUniqueId)) elif consequence.modal == "Never": assertions.append(Assertion( exclude=True, properties=antecedent + consequence.properties, sourceBeliefId=belief.beliefUniqueId )) return AssertionSet(assertions=assertions)
8,716
Python
.py
176
39.744318
128
0.673457
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,377
Cheemera.cpython-39.pyc
gmkung_Cheemera/python/__pycache__/Cheemera.cpython-39.pyc
a ÕT„e "ã@sòddlmZmZmZmZmZmZddlZddlZee efdœdd„Z Gdd„deƒZ Gdd „d eƒZ Gd d „d eƒZ Gd d „d eƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZee ee dœdd„Zeee edœdd„Zeee ee dœdd„Ze ee ed œd!d"„Zee ee ee d#œd$d%„Zee eed&œd'd(„Zee ee dœd)d*„Zee ee dœd+d„Zee ee eee d,œd-d.„Zeeed/œd0d1„Zeed2œd3d4„Zeed2œd5d6„ZdS)7é)Ú NamedTupleÚListÚOptionalÚAnyÚDictÚSetN)Ú request_bodyc Csdz0|d}|d}t|ƒ}t|ƒ}t||ƒ}|WSty^}zd|›�WYd}~Sd}~00dS)NÚexploreÚ beliefSetz0An error occurred while processing the request: )Únormalise_belief_setÚgenerate_assertionsÚexplore_assertionsÚ Exception)rr Ú belief_setZnormalised_belief_setÚ assertion_setZexplore_resultsÚerror©rú;/Users/guangmiankung/Documents/Cheema-v3/python/Cheemera.pyÚexplore_belief_sets rc@seZdZUeed<eed<dS)ÚPropertyÚvalenceÚsentenceN)Ú__name__Ú __module__Ú __qualname__ÚboolÚ__annotations__Ústrrrrrrs rc@s"eZdZUeed<eeed<dS)Ú ConsequenceÚmodalÚ propertiesN)rrrrrrrrrrrrs rc@s2eZdZUeed<eeed<eeeed<dS)ÚScenarioÚtypeÚ consequencesÚ antecedentsN)rrrrrrrrrrrrr! s  r!c@s.eZdZUeed<eed<eed<eed<dS)ÚBeliefÚscenarioÚbeliefUniqueIdÚoriginatingRuleSystemNameÚoriginatingRuleSystemUuidN)rrrr!rrrrrrr%%s r%c@s>eZdZUeeed<eed<eed<eed<eeed<dS)Ú BeliefSetÚbeliefsÚ beliefSetNameÚbeliefSetOwnerÚbeliefSetVersionÚblindReferenceExternalIdArrayN)rrrrr%rrrrrrrr*+s  r*c@s2eZdZUeed<eeed<dZee ed<dS)Ú AssertionÚexcluder NÚsourceBeliefId) rrrrrrrr2rrrrrrr02s  r0c@seZdZUeeed<dS)Ú AssertionSetÚ assertionsN)rrrrr0rrrrrr37s r3c@s:eZdZUeed<dZeeed<dZeee ed<dS)Ú ReasoningStepÚinferenceStepTypeNr2ÚdeducedProperty) rrrrrr2rr7rrrrrrr5:s r5c@s.eZdZUeed<eed<eeefed<dS)Ú ExploreResultÚ resultCodeÚ resultReasonÚresultsN)rrrrrrrrrrrr8?s r8)r ÚreturncCsdS©Nr©r rrrÚinvert_valencesFsr?)Ú assertionÚ explore_objr<cs|jot‡fdd„|jDƒƒS)Nc3s$|]‰t‡fdd„ˆDƒƒVqdS)c3s&|]}|jˆjko|jˆjkVqdSr=©rr©Ú.0Úobj©ÚproprrÚ <genexpr>Móz2is_assertion_excluded.<locals>.<genexpr>.<genexpr>N©Úany©rD©rArFrrHLsÿz(is_assertion_excluded.<locals>.<genexpr>)r1Úallr ©r@rArrMrÚis_assertion_excludedKsşrPcs‡fdd„|jDƒS)Ncs&g|]‰t‡fdd„ˆDƒƒsˆ‘qS)c3s&|]}|jˆjko|jˆjkVqdSr=rBrCrFrrrHRsz/calculate_residue.<locals>.<listcomp>.<genexpr>rJrLrMrFrÚ <listcomp>Rsÿz%calculate_residue.<locals>.<listcomp>r>rOrrMrÚcalculate_residueQsrR)ÚpropertyrAr<cst‡fdd„|DƒƒS)Nc3s|]}|jˆjkVqdSr=©rrC©rSrrrHWrIz"is_new_property.<locals>.<genexpr>)rN)rSrArrUrÚis_new_propertyVsrV)ÚresiduerAr<cs‡fdd„|DƒS)Ncs(g|] ‰t‡fdd„ˆDƒƒsˆj‘qS)c3s|]}ˆj|kVqdSr=rT)rDr©rErrrHZsz:calculate_secondary_residues.<locals>.<listcomp>.<genexpr>)rKrrLrMrXrrQZsÿz0calculate_secondary_residues.<locals>.<listcomp>r)rWrArrMrÚcalculate_secondary_residuesYsrY)r rr<c sh| ¡}tdddggdœd�}d}d}t tj|dd� ¡¡ ¡|ksP|dk�rdt tj|dd� ¡¡ ¡}|d7}|jdd…D]މt dd �}t ˆ|ƒrÊ|j ˆj d �}|j d  |¡d |j d <|Stˆ|ƒ}t|ƒdk�rJt|d|ƒ�rJt|ƒ}|j |d�}|j ˆj d �}|j d  |¡| |¡t‡fdd„|jDƒd�}q‚|j d t||ƒ¡q‚q&|S)NZSuccesszSuccessful with no errors foundT)ÚpossibleÚreasoningStepsÚarrayOfSecondaryResidues)r9r:r;é)Ú sort_keysZ Deductive)r6)r2r[FrZr)r7csg|]}|ˆkr|‘qSrr)rDÚa©r@rrrQ„rIz&explore_assertions.<locals>.<listcomp>©r4r\)Úcopyr8ÚhashlibZmd5ÚjsonÚdumpsÚencodeZ hexdigestr4r5rPÚ_replacer2r;ÚappendrRÚlenrVr?Úextendr3rY) r rZ discoveriesZ result_objZturnZ previous_md5Zreasoning_stepZ residue_objZdeducedrr`rr _sBıı *       ÿr cCsdd„|Dƒ ¡}t|ƒS)NcSsi|] }|j|“qSrrT©rDrGrrrÚ <dictcomp>“rIz*deduplicate_properties.<locals>.<dictcomp>)ÚvaluesÚlist)r Zunique_propertiesrrrÚdeduplicate_properties‘srocCsdd„|DƒS)NcSsg|]}t|j|j d�‘qS©rB©rrrrkrrrrQ—rIz#invert_valences.<locals>.<listcomp>rr>rrrr?–s)ÚfiltersÚ adjectivesr<cs‡fdd„|DƒS)Ncs&g|]}gˆ¢t|j|j d�‘‘qSrprq)rDZadj©rrrrrQšrIz,create_always_assertions.<locals>.<listcomp>r)rrrsrrtrÚcreate_always_assertions™sru)Úcompound_beliefr<csFˆjjdvr<ˆjjdkrdnd‰‡‡fdd„tˆjjƒDƒSˆgSdS)N©ÚMUTUAL_EXCLUSIONZMUTUAL_INCLUSIONrxÚNeverÚAlwayscsJg|]B\‰}ttd‡‡fdd„tˆjjƒDƒ|gd�ˆjˆjˆjd�‘qS)ÚIF_THENcs$g|]\}}ˆ|krtˆ|d�‘qS))rr )r)rDÚjÚfp)ÚiÚ modal_typerrrQ£sÿz/breakdown_belief.<locals>.<listcomp>.<listcomp>)r"r#r$)r&r'r(r))r%r!Ú enumerater&r$r'r(r))rDÚ antecedent©rvr)r~rrQŸsó  şúõz$breakdown_belief.<locals>.<listcomp>)r&r"r€r$)rvrr‚rÚbreakdown_beliefœs    òrƒ)rr<cCs\g}|jD]6}|jjdkr&| |¡q |jjdvr | t|ƒ¡q t||j|j|j |j d�S)Nr{rw)r+r,r-r.r/) r+r&r"rhrjrƒr*r,r-r.r/)rZnormalised_beliefsÚbeliefrrrr ²s    ûr c s®g}|jD]˜}|jjdkr |jjD]~‰|jjD]p}|jdkrxtˆ‡fdd„|jDƒƒ}|D]}| t d||j d�¡qZq.|jdkr.| t dˆ|j|j d�¡q.q"q t |d�S) Nr{rzcs$g|]}|jdd„ˆDƒvr|‘qS)cSsh|] }|j’qSrrT)rDr}rrrÚ <setcomp>ËrIz1generate_assertions.<locals>.<listcomp>.<setcomp>rTrk©r�rrrQËrIz'generate_assertions.<locals>.<listcomp>T)r1r r2ryra) r+r&r"r$r#rrur rhr0r'r3)rr4r„Z consequenceZ to_excludeÚitemrr†rr Âs&     ş ır ) Útypingrrrrrrrdrcrrrrr!r%r*r0r3r5r8r?rrPrRrVrYr rorurƒr r rrrrÚ<module>s0 2"
8,964
Python
.py
56
159.053571
1,089
0.405545
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,378
Cheemera.cpython-39.pyc
gmkung_Cheemera/python/__pycache__/Cheemera.cpython-39.pyc
a ÕT„e "ã@sòddlmZmZmZmZmZmZddlZddlZee efdœdd„Z Gdd„deƒZ Gdd „d eƒZ Gd d „d eƒZ Gd d „d eƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZGdd„deƒZee ee dœdd„Zeee edœdd„Zeee ee dœdd„Ze ee ed œd!d"„Zee ee ee d#œd$d%„Zee eed&œd'd(„Zee ee dœd)d*„Zee ee dœd+d„Zee ee eee d,œd-d.„Zeeed/œd0d1„Zeed2œd3d4„Zeed2œd5d6„ZdS)7é)Ú NamedTupleÚListÚOptionalÚAnyÚDictÚSetN)Ú request_bodyc Csdz0|d}|d}t|ƒ}t|ƒ}t||ƒ}|WSty^}zd|›�WYd}~Sd}~00dS)NÚexploreÚ beliefSetz0An error occurred while processing the request: )Únormalise_belief_setÚgenerate_assertionsÚexplore_assertionsÚ Exception)rr Ú belief_setZnormalised_belief_setÚ assertion_setZexplore_resultsÚerror©rú;/Users/guangmiankung/Documents/Cheema-v3/python/Cheemera.pyÚexplore_belief_sets rc@seZdZUeed<eed<dS)ÚPropertyÚvalenceÚsentenceN)Ú__name__Ú __module__Ú __qualname__ÚboolÚ__annotations__Ústrrrrrrs rc@s"eZdZUeed<eeed<dS)Ú ConsequenceÚmodalÚ propertiesN)rrrrrrrrrrrrs rc@s2eZdZUeed<eeed<eeeed<dS)ÚScenarioÚtypeÚ consequencesÚ antecedentsN)rrrrrrrrrrrrr! s  r!c@s.eZdZUeed<eed<eed<eed<dS)ÚBeliefÚscenarioÚbeliefUniqueIdÚoriginatingRuleSystemNameÚoriginatingRuleSystemUuidN)rrrr!rrrrrrr%%s r%c@s>eZdZUeeed<eed<eed<eed<eeed<dS)Ú BeliefSetÚbeliefsÚ beliefSetNameÚbeliefSetOwnerÚbeliefSetVersionÚblindReferenceExternalIdArrayN)rrrrr%rrrrrrrr*+s  r*c@s2eZdZUeed<eeed<dZee ed<dS)Ú AssertionÚexcluder NÚsourceBeliefId) rrrrrrrr2rrrrrrr02s  r0c@seZdZUeeed<dS)Ú AssertionSetÚ assertionsN)rrrrr0rrrrrr37s r3c@s:eZdZUeed<dZeeed<dZeee ed<dS)Ú ReasoningStepÚinferenceStepTypeNr2ÚdeducedProperty) rrrrrr2rr7rrrrrrr5:s r5c@s.eZdZUeed<eed<eeefed<dS)Ú ExploreResultÚ resultCodeÚ resultReasonÚresultsN)rrrrrrrrrrrr8?s r8)r ÚreturncCsdS©Nr©r rrrÚinvert_valencesFsr?)Ú assertionÚ explore_objr<cs|jot‡fdd„|jDƒƒS)Nc3s$|]‰t‡fdd„ˆDƒƒVqdS)c3s&|]}|jˆjko|jˆjkVqdSr=©rr©Ú.0Úobj©ÚproprrÚ <genexpr>Móz2is_assertion_excluded.<locals>.<genexpr>.<genexpr>N©Úany©rD©rArFrrHLsÿz(is_assertion_excluded.<locals>.<genexpr>)r1Úallr ©r@rArrMrÚis_assertion_excludedKsşrPcs‡fdd„|jDƒS)Ncs&g|]‰t‡fdd„ˆDƒƒsˆ‘qS)c3s&|]}|jˆjko|jˆjkVqdSr=rBrCrFrrrHRsz/calculate_residue.<locals>.<listcomp>.<genexpr>rJrLrMrFrÚ <listcomp>Rsÿz%calculate_residue.<locals>.<listcomp>r>rOrrMrÚcalculate_residueQsrR)ÚpropertyrAr<cst‡fdd„|DƒƒS)Nc3s|]}|jˆjkVqdSr=©rrC©rSrrrHWrIz"is_new_property.<locals>.<genexpr>)rN)rSrArrUrÚis_new_propertyVsrV)ÚresiduerAr<cs‡fdd„|DƒS)Ncs(g|] ‰t‡fdd„ˆDƒƒsˆj‘qS)c3s|]}ˆj|kVqdSr=rT)rDr©rErrrHZsz:calculate_secondary_residues.<locals>.<listcomp>.<genexpr>)rKrrLrMrXrrQZsÿz0calculate_secondary_residues.<locals>.<listcomp>r)rWrArrMrÚcalculate_secondary_residuesYsrY)r rr<c sh| ¡}tdddggdœd�}d}d}t tj|dd� ¡¡ ¡|ksP|dk�rdt tj|dd� ¡¡ ¡}|d7}|jdd…D]މt dd �}t ˆ|ƒrÊ|j ˆj d �}|j d  |¡d |j d <|Stˆ|ƒ}t|ƒdk�rJt|d|ƒ�rJt|ƒ}|j |d�}|j ˆj d �}|j d  |¡| |¡t‡fdd„|jDƒd�}q‚|j d t||ƒ¡q‚q&|S)NZSuccesszSuccessful with no errors foundT)ÚpossibleÚreasoningStepsÚarrayOfSecondaryResidues)r9r:r;é)Ú sort_keysZ Deductive)r6)r2r[FrZr)r7csg|]}|ˆkr|‘qSrr)rDÚa©r@rrrQ„rIz&explore_assertions.<locals>.<listcomp>©r4r\)Úcopyr8ÚhashlibZmd5ÚjsonÚdumpsÚencodeZ hexdigestr4r5rPÚ_replacer2r;ÚappendrRÚlenrVr?Úextendr3rY) r rZ discoveriesZ result_objZturnZ previous_md5Zreasoning_stepZ residue_objZdeducedrr`rr _sBıı *       ÿr cCsdd„|Dƒ ¡}t|ƒS)NcSsi|] }|j|“qSrrT©rDrGrrrÚ <dictcomp>“rIz*deduplicate_properties.<locals>.<dictcomp>)ÚvaluesÚlist)r Zunique_propertiesrrrÚdeduplicate_properties‘srocCsdd„|DƒS)NcSsg|]}t|j|j d�‘qS©rB©rrrrkrrrrQ—rIz#invert_valences.<locals>.<listcomp>rr>rrrr?–s)ÚfiltersÚ adjectivesr<cs‡fdd„|DƒS)Ncs&g|]}gˆ¢t|j|j d�‘‘qSrprq)rDZadj©rrrrrQšrIz,create_always_assertions.<locals>.<listcomp>r)rrrsrrtrÚcreate_always_assertions™sru)Úcompound_beliefr<csFˆjjdvr<ˆjjdkrdnd‰‡‡fdd„tˆjjƒDƒSˆgSdS)N©ÚMUTUAL_EXCLUSIONZMUTUAL_INCLUSIONrxÚNeverÚAlwayscsJg|]B\‰}ttd‡‡fdd„tˆjjƒDƒ|gd�ˆjˆjˆjd�‘qS)ÚIF_THENcs$g|]\}}ˆ|krtˆ|d�‘qS))rr )r)rDÚjÚfp)ÚiÚ modal_typerrrQ£sÿz/breakdown_belief.<locals>.<listcomp>.<listcomp>)r"r#r$)r&r'r(r))r%r!Ú enumerater&r$r'r(r))rDÚ antecedent©rvr)r~rrQŸsó  şúõz$breakdown_belief.<locals>.<listcomp>)r&r"r€r$)rvrr‚rÚbreakdown_beliefœs    òrƒ)rr<cCs\g}|jD]6}|jjdkr&| |¡q |jjdvr | t|ƒ¡q t||j|j|j |j d�S)Nr{rw)r+r,r-r.r/) r+r&r"rhrjrƒr*r,r-r.r/)rZnormalised_beliefsÚbeliefrrrr ²s    ûr c s®g}|jD]˜}|jjdkr |jjD]~‰|jjD]p}|jdkrxtˆ‡fdd„|jDƒƒ}|D]}| t d||j d�¡qZq.|jdkr.| t dˆ|j|j d�¡q.q"q t |d�S) Nr{rzcs$g|]}|jdd„ˆDƒvr|‘qS)cSsh|] }|j’qSrrT)rDr}rrrÚ <setcomp>ËrIz1generate_assertions.<locals>.<listcomp>.<setcomp>rTrk©r�rrrQËrIz'generate_assertions.<locals>.<listcomp>T)r1r r2ryra) r+r&r"r$r#rrur rhr0r'r3)rr4r„Z consequenceZ to_excludeÚitemrr†rr Âs&     ş ır ) Útypingrrrrrrrdrcrrrrr!r%r*r0r3r5r8r?rrPrRrVrYr rorurƒr r rrrrÚ<module>s0 2"
8,964
Python
.pyt
56
159.053571
1,089
0.405545
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,379
_stackHas.js
gmkung_Cheemera/node_modules/lodash/_stackHas.js
/** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas;
323
Python
.tac
13
23
80
0.679612
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,380
_stackSet.js
gmkung_Cheemera/node_modules/lodash/_stackSet.js
var ListCache = require('./_ListCache'), Map = require('./_Map'), MapCache = require('./_MapCache'); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet;
853
Python
.tac
31
24.387097
60
0.634921
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,381
_stackClear.js
gmkung_Cheemera/node_modules/lodash/_stackClear.js
var ListCache = require('./_ListCache'); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear;
254
Python
.tac
13
17.615385
48
0.686192
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,382
_stackGet.js
gmkung_Cheemera/node_modules/lodash/_stackGet.js
/** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet;
271
Python
.tac
13
19
51
0.669261
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,383
_stackDelete.js
gmkung_Cheemera/node_modules/lodash/_stackDelete.js
/** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete;
405
Python
.tac
16
22.9375
76
0.679587
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,384
_Stack.js
gmkung_Cheemera/node_modules/lodash/_Stack.js
var ListCache = require('./_ListCache'), stackClear = require('./_stackClear'), stackDelete = require('./_stackDelete'), stackGet = require('./_stackGet'), stackHas = require('./_stackHas'), stackSet = require('./_stackSet'); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack;
734
Python
.tac
24
28.208333
57
0.700141
gmkung/Cheemera
8
1
1
AGPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,385
ocr.py
yousefmrashad_bookipedia/preprocessing/ocr.py
# Utils from root_config import * from utils.init import * from utils.hocr import HocrTransform # ===================================================================== # # OCR class OCR: def __init__(self, doc_path: str, scale=5): self.doc_path = doc_path self.scale = scale from doctr.io import DocumentFile self.docs = DocumentFile.from_pdf(doc_path, scale=scale) # ---------------------------------------------- # @staticmethod def filter_image(img: np.ndarray, kernel_size=55, white_point=120, black_point=70) -> np.ndarray: if (kernel_size % 2 == 0): kernel_size += 1 # Create a kernel for filtering kernel = np.ones((kernel_size, kernel_size), np.float32) / (kernel_size * kernel_size) filtered = cv.filter2D(img, -1, kernel) # Enhance the image by subtracting the filtered image and adding a constant value filtered = img.astype(np.float32) - filtered.astype(np.float32) filtered = filtered + 127 * np.ones(img.shape, np.uint8) filtered = filtered.astype(np.uint8) # Apply thresholding to obtain a binary image _, img = cv.threshold(filtered, white_point, 255, cv.THRESH_TRUNC) # Map pixel values to a new range img = map_values(img.astype(np.int32), 0, white_point, 0, 255).astype(np.uint8) img = map_values(img.astype(np.int32), black_point, 255, 0, 255) # Apply thresholding to remove low intensity pixels _, img = cv.threshold(img, 0, 255, cv.THRESH_TOZERO) img = img.astype(np.uint8) # Convert image to LAB color space and perform color manipulation lab = cv.cvtColor(img, cv.COLOR_BGR2LAB) (l, a, b) = cv.split(lab) img = cv.add(cv.subtract(l, b), cv.subtract(l, a)) # Apply sharpening filter sharpened = cv.filter2D(img, -1, np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])) # Convert image to RGB format rgb_image = np.stack([sharpened] * 3, axis=-1) return rgb_image # ---------------------------------------------- # @staticmethod def correct_skew(img: np.ndarray) -> np.ndarray: # Convert image to grayscale gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # Apply adaptive thresholding to obtain a binary image _, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU) # Find contours in the binary image contours, _ = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) # Find the largest contour largest_contour = max(contours, key=cv.contourArea) # Find the minimum area rectangle that encloses the contour rect = cv.minAreaRect(largest_contour) angle = rect[-1] # Rotate the image to correct the skew rows, cols = img.shape[:2] rotation_matrix = cv.getRotationMatrix2D((cols / 2, rows / 2), angle, 1) corrected_image = cv.warpAffine(img, rotation_matrix, (cols, rows), flags=cv.INTER_LINEAR) return corrected_image # ---------------------------------------------- # # OCR def ocr(self) -> Document: from doctr.models import ocr_predictor model = ocr_predictor(det_arch=DETECTION_MODEL, reco_arch=RECOGNITION_MODEL, assume_straight_pages=True, pretrained=True, export_as_straight_boxes=True).cuda() self.result = model.forward(self.docs) # ---------------------------------------------- # # HOCR def hocr(self): # Export OCR results as XML xml_outputs = self.result.export_as_xml() # Create a new PDF document self.pdf_output = Pdf.new() # Iterate over each page in the OCR results for (xml, img) in zip(xml_outputs, self.docs): # Create an HocrTransform object hocr = HocrTransform(hocr=xml[1], dpi=360) # Convert the HOCR and image to PDF pdf = hocr.to_pdf(image = PIL.Image.fromarray(img), invisible_text=True) # Append the PDF pages to the output document self.pdf_output.pages.extend(pdf.pages) # ---------------------------------------------- # # Save the output PDF with HOCR format def save_hocr_doc(self) -> None: # hocr_doc_path = self.doc_path.replace(".pdf", "_hocr.pdf") self.pdf_output.save(self.doc_path) # ---------------------------------------------- # # OCR Pipeline def apply_ocr(self, deskew=False, filter=False) -> None: if (filter): self.docs = [OCR.filter_image(page) for page in self.docs] if (deskew): self.docs = [OCR.correct_skew(page) for page in self.docs] self.ocr() self.hocr() self.save_hocr_doc() # ---------------------------------------------- #
5,121
Python
.py
98
41.193878
102
0.558872
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,386
embedding.py
yousefmrashad_bookipedia/preprocessing/embedding.py
# Utils from root_config import * from utils.init import * # ===================================================================== # # HFEmbedding Model class HFEmbedding(Embeddings): def __init__(self, model_name=EMBEDDING_MODEL_NAME, prompt=RETRIEVAL_PROMPT): self.model = SentenceTransformer(model_name, trust_remote_code=True).cuda() self.prompt = prompt def embed_documents(self, texts: list[str]): return self.model.encode(texts).tolist() def embed_query(self, text: str): text = self.prompt + text if (self.prompt) else text return self.model.encode(text).squeeze().tolist() # --------------------------------------------------------------------- #
744
Python
.py
16
40
84
0.533887
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,387
root_config.py
yousefmrashad_bookipedia/preprocessing/root_config.py
# -- Setup directory for utils package -- # import sys, os root_path = os.path.dirname(os.path.dirname(__file__)) sys.path.append(root_path) # =================================================== #
200
Python
.py
5
38.4
55
0.505102
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,388
document.py
yousefmrashad_bookipedia/preprocessing/document.py
# Utils from root_config import * from utils.init import * # ===================================================================== # class Document: def __init__(self, doc_path: str, doc_id: str, lib_doc:bool = False): self.doc_path = doc_path self.doc_id = doc_id self.doc = fitz.open(doc_path) if (lib_doc): self.text_based = True else: self.text_based = calculate_imagebox_percentage(self.doc) < 0.5 # ---------------------------------------------- # def get_text_based_document(self): from preprocessing.ocr import OCR OCR(self.doc_path).apply_ocr() # ---------------------------------------------- # def load_and_split(self): if(self.text_based): text_splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, length_function=count_tokens, separators=MD_SEPARATORS, is_separator_regex=True) md_texts = [] metadatas = [] for i in range(self.doc.page_count): metadata = {} md_texts.append(to_markdown(self.doc, [i])) metadata['source_id'] = self.doc_id metadata['page'] = i metadatas.append(metadata) self.chunks = text_splitter.create_documents(md_texts, metadatas) else: text_splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, length_function=count_tokens, separators=SEPARATORS, is_separator_regex=True) self.chunks = PyPDFLoader(self.doc_path).load_and_split(text_splitter) for chunk in self.chunks: chunk.metadata["source_id"] = self.doc_id # ---------------------------------------------- # def generate_embeddings(self, embedder: Embeddings): self.embeddings = embedder.embed_documents([chunk.page_content for chunk in self.chunks]) # ---------------------------------------------- # def store_in_db(self, client: WeaviateClient): collection = client.collections.get(DB_NAME) # Check if the source id already exists exist_filter = wvc.query.Filter.by_property("source_id").equal(self.doc_id) not_exist = (len((collection.query.fetch_objects(filters=exist_filter, limit=1).objects)) == 0) if (not_exist): objs = [] l1, l2 = (0, 0) for i, chunk in enumerate(self.chunks): if (i != 0) and (i % L1 == 0): l1 += 1 if (i != 0) and (i % L2 == 0): l2 += 1 properties = { "index": i, "source_id": chunk.metadata["source_id"], "page_no": chunk.metadata["page"]+1, "text": chunk.page_content, "l1": l1, "l2": l2 } obj = wvc.data.DataObject(properties=properties, vector=self.embeddings[i]) objs.append(obj) collection.data.insert_many(objs) # ---------------------------------------------- # def process_document(self, embedder: Embeddings, client: WeaviateClient): self.load_and_split() self.generate_embeddings(embedder) self.store_in_db(client) # --------------------------------------------------------------------- #
3,742
Python
.py
71
37.028169
116
0.46984
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,389
weaviate_retriever.py
yousefmrashad_bookipedia/rag/weaviate_retriever.py
# Utils from root_config import * from utils.init import * # ================================================== # class Weaviate(VectorStore): def __init__(self, client: WeaviateClient, embedder: Embeddings) -> None: self.client = client self.embedder = embedder self.collection = self.client.collections.get(DB_NAME) # -------------------------------------------------- # # -- Main Methods -- # # Response to documents def objects_to_docs(self, objects: list[Object]) -> list[Document]: docs = [] for obj in objects: text = obj.properties["text"] metadata = {"source_id": obj.properties["source_id"], "page_no": obj.properties["page_no"]} docs.append(Document(page_content=text, metadata=metadata)) return docs # -------------------------------------------------- # def similarity_search(self, query: str, source_ids: list, auto_merge =False, k = 16, top_k = 5, alpha=0.5) -> list[Document]: query_emb = self.embedder.embed_query(query) objects = self.collection.query.hybrid(query=query, vector=query_emb, filters=ids_filter(source_ids), limit=k, alpha=alpha).objects objects = sorted(objects, key=lambda obj: obj.properties["index"]) if (auto_merge): merged_objects = [] for source_id in source_ids: merged_objects.extend(self.auto_merge(objects, source_id)) docs = self.objects_to_docs(merged_objects) docs = self.rerank_docs(query, docs, top_k) else: docs = self.objects_to_docs(objects) return docs # -------------------------------------------------- # def similarity_search_with_relevance_scores(self, query: str, source_ids: list, k=5, alpha=0.5) -> list[tuple[Document, float]]: query_emb = self.embedder.embed_query(query) objects = self.collection.query.hybrid(query=query, vector=query_emb, filters=ids_filter(source_ids), limit=k, alpha=alpha, return_metadata=wvc.query.MetadataQuery(score=True)).objects objects = sorted(objects, key=lambda obj: obj.properties["index"]) scores = [obj.metadata.score for obj in objects] docs = self.objects_to_docs(objects) docs = zip(docs, scores) return list(docs) # -------------------------------------------------- # def max_marginal_relevance_search(self, query: str, source_ids: list, k=5, fetch_k=20, lambda_mult=0.5) -> list[tuple[Document, float]]: query_emb = self.embedder.embed_query(query) objects = self.collection.query.near_vector(near_vector=query_emb, filters=ids_filter(source_ids), limit=fetch_k, return_metadata=wvc.query.MetadataQuery(distance=True), include_vector= True).objects objects = sorted(objects, key=lambda obj: obj.properties["index"]) embeddings = [obj.vector["default"] for obj in objects] mmr_selected = maximal_marginal_relevance(np.array(query_emb), embeddings, k=k, lambda_mult=lambda_mult) objects = [objects[i] for i in mmr_selected] docs = self.objects_to_docs(objects) return docs # -------------------------------------------------- # def delete(self, source_id: str): self.collection.data.delete_many(where=id_filter(source_id)) # -------------------------------------------------- # # -- Advanced Methods -- # # Re-rank Results def rerank_docs(self, query: str, docs: list[Document], top_k :int) -> list[Document]: model = CrossEncoder(RERANKER_MODEL_NAME, trust_remote_code=True) # Prepare the query-document pairs for the model documents = [doc.page_content for doc in docs] # Rank docs against query results = model.rank(query, documents, return_documents= False, top_k = top_k) indices = [res['corpus_id'] for res in results] docs = [docs[i] for i in indices] return docs # -------------------------------------------------- # # Auto-Merge def auto_merge(self, objects: list[Object], source_id: str) -> list[Object]: source_id_filter = id_filter(source_id) # Count retrieved level 1 & level 2 number l1_count = Counter(obj.properties["l1"] for obj in objects) l2_count = Counter(obj.properties["l2"] for obj in objects) # Get level 0 & level 1 & level 2 chunks number to merge l0_chunks_keys = [key for key, value in l1_count.items() if (value <= (L1 // 2))] l1_chunks_keys = [key for key, value in l1_count.items() if (value >= (L1 // 2) + 1)] l2_chunks_keys = [key for key, value in l2_count.items() if (value >= (L2 // 2) + 1)] # Exclude l1 chunks from l2 merged chunks l_ratio = L2 // L1 l1_chunks_keys = [c for c in l1_chunks_keys if all(c not in range(p*l_ratio, (p+1)*l_ratio) for p in l2_chunks_keys)] # Get level 0 chunks l0_chunks = [obj for obj in objects if (obj.properties["l1"] in l0_chunks_keys)] # Get level 1 chunks if (l1_chunks_keys): l1_filters = wvc.query.Filter.by_property("l1").contains_any(l1_chunks_keys) & source_id_filter l1_chunks = self.collection.query.fetch_objects(filters=l1_filters, limit=FETCHING_LIMIT, sort=SORT).objects l1_chunks = self.merge_chunks(l1_chunks, l="l1") else: l1_chunks = [] # Get level 2 chunks if (l2_chunks_keys): l2_filters = wvc.query.Filter.by_property("l2").contains_any(l2_chunks_keys) & source_id_filter l2_chunks = self.collection.query.fetch_objects(filters=l2_filters, limit=FETCHING_LIMIT, sort=SORT).objects l2_chunks = self.merge_chunks(l2_chunks, l="l2") else: l2_chunks = [] # Return all levels chunks return l0_chunks + l1_chunks + l2_chunks # -------------------------------------------------- # # -- Auto-Merge [Help Functions] -- # def merge_chunks(self, objects: list[Object], level: str) -> list[Object]: object_dict = {} for obj in objects: key = obj.properties[level] if (key in object_dict): object_dict[key]["text"] += (" " + obj.properties["text"]) else: object_props = { "text": obj.properties["text"], "source_id": obj.properties["source_id"], "page_no": obj.properties["page_no"] } object_dict[key] = object_props # Convert object dictionary to weaviate object chunks_objects = [] for obj_props in object_dict.values(): obj = Object(properties=obj_props, uuid=None, metadata=None, references=None, vector=None, collection=None) chunks_objects.append(obj) return chunks_objects # -------------------------------------------------- # # -- Retriever Methods -- # def _get_retriever_tags(self) -> list[str]: tags = [self.__class__.__name__] if self.embeddings: tags.append(self.embeddings.__class__.__name__) return tags # -------------------------------------------------- # def as_retriever(self, **kwargs) -> VectorStoreRetriever: tags = kwargs.pop("tags", None) or [] tags.extend(self._get_retriever_tags()) return VectorStoreRetriever(vectorstore=self, **kwargs, tags=tags) # -------------------------------------------------- # # -- Abstract Methods -- # def add_texts(self, texts, metadatas=None, **kwargs): return def from_texts(cls, texts, embedding, metadatas=None, **kwargs): return # -------------------------------------------------- #
8,416
Python
.py
146
44.410959
141
0.528524
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,390
web_weaviate.py
yousefmrashad_bookipedia/rag/web_weaviate.py
# Utils from root_config import * from utils.init import * # ===================================================================== # class WebWeaviate(VectorStore): def __init__(self, client: WeaviateClient, embedder: Embeddings) -> None: self.client = client self.embedder = embedder self.collection = self.client.collections.get("web_research") # ---------------------------------------------- # # -- Main Methods -- # def add_texts(self, texts: list[str], metadatas: list[dict] = None) -> list[str]: embeddings = self.embedder.embed_documents(texts) ids = [] with self.collection.batch.dynamic() as batch: for i, metadatas in enumerate(metadatas): metadatas['text'] = texts[i] id = batch.add_object(properties=metadatas, vector=embeddings[i]) ids.append(id) return ids # ---------------------------------------------- # def similarity_search(self, query: str, k=5, alpha=0.9) -> list[Document]: query_emb = self.embedder.embed_query(query) objects = self.collection.query.hybrid(query=query, vector=query_emb, limit=k, alpha=alpha).objects docs = self.objects_to_docs(objects) return docs # ---------------------------------------------- # # -- Utility Methods -- # # Delete all documents in the collection def delete(self): response = self.collection.query.fetch_objects(limit=FETCHING_LIMIT, return_properties=[]) ids = [o.uuid for o in response.objects] if (ids): self.collection.data.delete_many(where=ids_filter(ids)) # ---------------------------------------------- # # Response to documents def objects_to_docs(self, objects: list[Object]) -> list[Document]: docs = [] for obj in objects: text = obj.properties["text"] metadata = {key: value for key, value in obj.properties.items() if key != "text"} docs.append(Document(page_content=text, metadata=metadata)) return docs # -- Abstract Methods -- # def from_texts(cls, texts, embedding, metadatas=None, **kwargs): return # ---------------------------------------------- #
2,331
Python
.py
47
40.12766
98
0.529884
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,391
rag_pipeline.py
yousefmrashad_bookipedia/rag/rag_pipeline.py
# Utils from root_config import * from utils.init import * from rag.web_weaviate import WebWeaviate from rag.web_researcher import WebResearchRetriever from rag.weaviate_retriever import Weaviate # ===================================================================== # class RAGPipeline: def __init__(self, embedding_model: Embeddings, client: WeaviateClient) -> None: # self.llm = ChatOpenAI(model_name=LLM_MODEL_NAME, temperature=0, streaming=True, openai_api_key=OPEN_AI_KEY) self.llm = GoogleGenerativeAI(model=LLM_MODEL_NAME, google_api_key= GOOGLE_API_KEY, temperature= 0) self.embedding_model = embedding_model self.client = client self.db = Weaviate(self.client, self.embedding_model) self.web_db = WebWeaviate(self.client, embedder=self.embedding_model) self.search = DuckDuckGoSearchAPIWrapper(backend="html") self.web_retriever = WebResearchRetriever.from_llm(vectorstore=self.web_db, llm=self.llm, search=self.search) # --------------------------------------------------------------------- # def get_page_text(self, doc_id: str, page_no: int) -> str: col = self.client.collections.get(DB_NAME) filters = id_filter(doc_id) & page_filter(page_no) res = col.query.fetch_objects(filters=filters, limit=FETCHING_LIMIT, sort=SORT) texts = [o.properties["text"] for o in res.objects] text = merge_chunks(texts) return text # --------------------------------------------------------------------- # # -- Summary Methods -- # def summary_splitter(self, text: str) -> list[str]: token_count = count_tokens(text) no_splits = math.ceil(token_count / SUMMARY_TOKEN_LIMIT) chunk_size = token_count // no_splits text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=CHUNK_OVERLAP, length_function=count_tokens, separators=SEPARATORS, is_separator_regex=True) chunks = text_splitter.split_text(text) return chunks # --------------------------------------------------------------------- # async def summarize_text(self, text: str) -> AsyncIterator[str]: SUMMARY_PROMPT = ChatPromptTemplate.from_template(""" You are an assistant tasked with summarizing the provided text. Your goal is to create a concise summary that captures the essence of the original content, focusing on the most important points and key information. Please ensure that the summary is clear, informative, and easy to understand. THE INPUT TEXT: ```{text}``` """) self.summary_chain = SUMMARY_PROMPT | self.llm | StrOutputParser() chunks = self.summary_splitter(text) chunks_summaries = await asyncio.gather(*(self.summary_chain.ainvoke({"text": t}) for t in chunks)) joined_summary = '\n\n'.join(chunks_summaries) # Recur if combined sub-summary size still exceeds limit if(count_tokens(joined_summary) > SUMMARY_TOKEN_LIMIT): joined_summary = await self.summarize_text(joined_summary) summary = self.summary_chain.astream({"text": joined_summary}) return summary # --------------------------------------------------------------------- # async def summarize_pages(self, doc_id: str, page_nos: list[int]) -> AsyncIterator[str]: pages_text = '\n\n'.join([self.get_page_text(doc_id , page_no) for page_no in page_nos]) return await self.summarize_text(text=pages_text) # --------------------------------------------------------------------- # # Chat Summary # def generate_chat_summary(self, user_prompt: str, llm_response: str, prev_chat_summary: str): # Define the chat summary prompt template CHAT_SUMMARY_PROMPT = ChatPromptTemplate.from_template( """You are an assistant tasked with optimizing the process of summarizing user chat . Given the previous chat history, user prompt, and LLM response, summarize the chat effectively. Focus on new information and important highlights. Previous Chat Summary: ```{chat_summary}``` User Question: ```{user_prompt}``` LLM Response: ```{llm_response}```""", ) # Create the chat summary chain chat_summary_chain = CHAT_SUMMARY_PROMPT | self.llm # Invoke the chat summary chain with the chat, retrieving_query, and response llm_input = { "chat_summary": prev_chat_summary, "user_prompt": user_prompt, "llm_response": llm_response } chat_summary = chat_summary_chain.invoke(llm_input) # Return the content of the chat summary return chat_summary # --------------------------------------------------------------------- # # -- Retrieval Methods -- # def generate_retrieval_query(self, user_prompt: str, chat_summary: str) -> tuple[str, str]: retrieval_method_schema = ResponseSchema(name="retrieval_method", description="This is a string can only be one of the following words: (vectorstore, web, vectorstore+web, none)") retrieval_query_schema = ResponseSchema(name="retrieval_query", description="This is the retrieval query") response_schemas = [retrieval_method_schema, retrieval_query_schema] output_parser = StructuredOutputParser.from_response_schemas(response_schemas) format_instructions = output_parser.get_format_instructions() # Define the retrieval query template RETRIEVAL_QUERY_PROMPT = ChatPromptTemplate.from_template( """You are an intelligent assistant responsible for determining the appropriate method to retrieve information based on a given user prompt and a chat summary. Here are the steps to follow: (1) Extract the Retrieval Method: Analyze the user prompt and chat summary to determine if information retrieval is needed. Choose from the following methods: - Retrieval: The user query is not covered by the chat history and could use information from external sources (i.e. the query is very specific) OR the user provides an excerpt, OR the user explicitly mentions "this document/book/article" or something similar. - Web: The user explicitly asks for sources from the web. - Hybrid: The requirements for "Retrieval" are met, AND the user explicitly asks for web sources. - None: The user query is already covered by the chat history, and doesn't need further information from external sources, OR is a general request. (2) Generate the Retrieval Query: Formulate a precise and effective retrieval query based on the user's prompt and the chat summary. User Prompt: ```{user_prompt}``` Chat Summary: ```{chat_summary}``` {format_instructions} """ ) # Create the retrieval query chain retrieval_query_chain = RETRIEVAL_QUERY_PROMPT | self.llm # Invoke the retrieval query chain with the user prompt and chat summary response = retrieval_query_chain.invoke({"user_prompt": user_prompt, "chat_summary": chat_summary, "format_instructions": format_instructions}) response_dict = output_parser.parse(response) # Return the content of the retrieval query return response_dict["retrieval_method"], response_dict["retrieval_query"] # --------------------------------------------------------------------- # # Context generation methods def generate_vecdb_context(self, retrieval_query: str, doc_ids: list[str]) -> tuple[list[str], list[dict[str, str]]]: docs = self.db.similarity_search(query=retrieval_query, source_ids=doc_ids, auto_merge=True) content = [doc.page_content for doc in docs] metadata = [{"doc_id": doc.metadata['source_id'], "page_no": doc.metadata['page_no'], "text": doc.page_content} for doc in docs] return content, metadata def generate_web_context(self, retrieval_query: str, rerank=True) -> tuple[list[str], list[str]]: if (rerank): docs = self.web_retriever.invoke(retrieval_query, k=3) docs = self.db.rerank_docs(retrieval_query, docs, top_k=5) else: docs = self.web_retriever.invoke(retrieval_query, k=2) content = [doc.page_content for doc in docs] metadata = list(set([doc.metadata['source'] for doc in docs])) return content, metadata # --------------------------------------------------------------------- # def generate_context(self, retrieval_method: str, retrieval_query: str, doc_ids: list[str] = None, enable_web_retrieval=False) -> tuple[str, dict[str, str]]: # Generate vectorestore context vecdb_context, vecdb_metadata = [], [] if (retrieval_method in ("Retrieval", "retrieval", "Hybrid", "hybrid")) and (doc_ids): vecdb_context, vecdb_metadata = self.generate_vecdb_context(retrieval_query, doc_ids) # Generate web context web_context , web_metadata = [], [] if (retrieval_method in ("Web", "web", "Hybrid", "hybrid")) or (enable_web_retrieval): web_context, web_metadata = self.generate_web_context(retrieval_query) # Combine the contexts context = vecdb_context + web_context context = '\n'.join(context) metadata = {"doc_sources": vecdb_metadata, "web_sources": web_metadata} return context, metadata # --------------------------------------------------------------------- # def generate_answer(self, user_prompt: str, chat: str, context: str) -> AsyncIterator[str]: QA_PROMPT = ChatPromptTemplate.from_template( """You are an assistant tasked with answering user question. Given the previous chat history, user question, and relevant context, provide a clear, concise, and informative answer. Your response should be structured in a way that is easy to understand and directly addresses the user's question. Previous Chat History: ```{chat}``` User Question: ```{user_prompt}``` Relevant Context: ```{context}``` """ ) qa_chain = QA_PROMPT | self.llm | StrOutputParser() llm_input = { "user_prompt": user_prompt, "context": context, "chat": chat } return qa_chain.astream(llm_input) # --------------------------------------------------------------------- #
11,021
Python
.py
166
54.771084
272
0.602599
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,392
root_config.py
yousefmrashad_bookipedia/rag/root_config.py
# -- Setup directory for utils package -- # import sys, os root_path = os.path.dirname(os.path.dirname(__file__)) sys.path.append(root_path) # =================================================== #
200
Python
.py
5
38.4
55
0.505102
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,393
web_researcher.py
yousefmrashad_bookipedia/rag/web_researcher.py
import logging import re from typing import List, Optional from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper from langchain_community.document_loaders.async_html import AsyncHtmlLoader from langchain_community.document_transformers import Html2TextTransformer from langchain_community.llms.llamacpp import LlamaCpp from langchain_core.callbacks import ( AsyncCallbackManagerForRetrieverRun, CallbackManagerForRetrieverRun, ) from langchain_core.documents import Document from langchain_core.language_models import BaseLLM from langchain_core.output_parsers import BaseOutputParser from langchain_core.prompts import BasePromptTemplate, PromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field from langchain_core.retrievers import BaseRetriever from langchain_core.vectorstores import VectorStore from langchain_text_splitters import RecursiveCharacterTextSplitter, TextSplitter from langchain.chains.llm import LLMChain from langchain.chains.prompt_selector import ConditionalPromptSelector logger = logging.getLogger(__name__) class SearchQueries(BaseModel): """Search queries to research for the user's goal.""" queries: List[str] = Field( ..., description="List of search queries to look up on DuckDuckGo" ) DEFAULT_LLAMA_SEARCH_PROMPT = PromptTemplate( input_variables=["question"], template="""<<SYS>> \n You are an assistant tasked with improving DuckDuckGo search \ results. \n <</SYS>> \n\n [INST] Generate THREE DuckDuckGo search queries that \ are similar to this question. The output should be a numbered list of questions \ and each should have a question mark at the end: \n\n {question} [/INST]""", ) DEFAULT_SEARCH_PROMPT = PromptTemplate( input_variables=["question"], template="""You are an assistant tasked with improving DuckDuckGo search \ results. Generate THREE DuckDuckGo search queries that are similar to \ this question. The output should be a numbered list of questions and each \ should have a question mark at the end: {question}""", ) class QuestionListOutputParser(BaseOutputParser[List[str]]): """Output parser for a list of numbered questions.""" def parse(self, text: str) -> List[str]: lines = re.findall(r"\d+\..*?(?:\n|$)", text) return lines class WebResearchRetriever(BaseRetriever): """`DuckDuckGo Search API` retriever.""" # Inputs vectorstore: VectorStore = Field( ..., description="Vector store for storing web pages" ) llm_chain: LLMChain search: DuckDuckGoSearchAPIWrapper = Field(..., description="DuckDuckGo Search API Wrapper") num_search_results: int = Field(1, description="Number of pages per DuckDuckGo search") text_splitter: TextSplitter = Field( RecursiveCharacterTextSplitter(chunk_size=480, chunk_overlap=32), description="Text splitter for splitting web pages into chunks", ) url_database: List[str] = Field( default_factory=list, description="List of processed URLs" ) @classmethod def from_llm( cls, vectorstore: VectorStore, llm: BaseLLM, search: DuckDuckGoSearchAPIWrapper, prompt: Optional[BasePromptTemplate] = None, num_search_results: int = 1, text_splitter: RecursiveCharacterTextSplitter = RecursiveCharacterTextSplitter( chunk_size=512, chunk_overlap=64 ), ) -> "WebResearchRetriever": """Initialize from llm using default template. Args: vectorstore: Vector store for storing web pages llm: llm for search question generation search: DuckDuckGoSearchAPIWrapper prompt: prompt to generating search questions num_search_results: Number of pages per DuckDuckGo search text_splitter: Text splitter for splitting web pages into chunks Returns: WebResearchRetriever """ if not prompt: QUESTION_PROMPT_SELECTOR = ConditionalPromptSelector( default_prompt=DEFAULT_SEARCH_PROMPT, conditionals=[ (lambda llm: isinstance(llm, LlamaCpp), DEFAULT_LLAMA_SEARCH_PROMPT) ], ) prompt = QUESTION_PROMPT_SELECTOR.get_prompt(llm) # Use chat model prompt llm_chain = LLMChain( llm=llm, prompt=prompt, output_parser=QuestionListOutputParser(), ) return cls( vectorstore=vectorstore, llm_chain=llm_chain, search=search, num_search_results=num_search_results, text_splitter=text_splitter, ) def clean_search_query(self, query: str) -> str: # Some search tools (e.g., DuckDuckGo) will # fail to return results if query has a # leading digit: 1. "LangCh..." # Check if the first character is a digit if query[0].isdigit(): # Find the position of the first quote first_quote_pos = query.find('"') if first_quote_pos != -1: # Extract the part of the string after the quote query = query[first_quote_pos + 1 :] # Remove the trailing quote if present if query.endswith('"'): query = query[:-1] return query.strip() def search_tool(self, query: str, num_search_results: int = 1) -> List[dict]: """Returns num_search_results pages per DuckDuckGo search.""" query_clean = self.clean_search_query(query) result = self.search.results(query_clean, num_search_results) return result def _get_relevant_documents( self, query: str, k: int = 2, *, run_manager: CallbackManagerForRetrieverRun, ) -> List[Document]: """Search DuckDuckGo for documents related to the query input. Args: query: user query Returns: Relevant documents from all various urls. """ # Get search questions logger.info("Generating questions for DuckDuckGo Search ...") result = self.llm_chain.invoke({"question": query}) logger.info(f"Questions for DuckDuckGo Search (raw): {result}") questions = result["text"] logger.info(f"Questions for DuckDuckGo Search: {questions}") # Get urls logger.info("Searching for relevant urls...") urls_to_look = [] for query in questions: # DuckDuckGo search search_results = self.search_tool(query, self.num_search_results) logger.info("Searching for relevant urls...") logger.info(f"Search results: {search_results}") for res in search_results: if res.get("link", None): urls_to_look.append(res["link"]) # Relevant urls urls = set(urls_to_look) # Check for any new urls that we have not processed new_urls = list(urls.difference(self.url_database)) logger.info(f"New URLs to load: {new_urls}") # Load, split, and add new urls to vectorstore if new_urls: loader = AsyncHtmlLoader(new_urls, ignore_load_errors=True) html2text = Html2TextTransformer() logger.info("Indexing new urls...") docs = loader.load() docs = list(html2text.transform_documents(docs)) docs = self.text_splitter.split_documents(docs) self.vectorstore.add_documents(docs) self.url_database.extend(new_urls) # Search for relevant splits logger.info("Grabbing most relevant splits from urls...") docs = [] for query in questions: docs.extend(self.vectorstore.similarity_search(query, k=k)) # Get unique docs unique_documents_dict = { (doc.page_content, tuple(sorted(doc.metadata.items()))): doc for doc in docs } unique_documents = list(unique_documents_dict.values()) # self.vectorstore.delete() return unique_documents async def _aget_relevant_documents( self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun, ) -> List[Document]: raise NotImplementedError
8,352
Python
.py
190
35.473684
96
0.664247
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,394
config.py
yousefmrashad_bookipedia/utils/config.py
# Using PyTorch import os os.environ["USE_TORCH"] = "1" # --------------------------------------------------------------------- # # -- Modules -- # # Basics import torch import re, json, math, requests, asyncio from collections import Counter import math import logging # Image Preprocessing import numpy as np import cv2 as cv # HOCR import PIL.Image from pikepdf import Pdf # Document Loading import fitz import tiktoken from pdf4llm import to_markdown from langchain_community.document_loaders.pdf import PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter # Embeddings from sentence_transformers import SentenceTransformer # Weaviate Class import weaviate import weaviate.classes as wvc from weaviate.collections.classes.grpc import Sort from langchain_core.vectorstores import VectorStore, VectorStoreRetriever from langchain_community.vectorstores.utils import maximal_marginal_relevance from sentence_transformers import CrossEncoder from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper from langchain.output_parsers import ResponseSchema from langchain.output_parsers import StructuredOutputParser # LLM from langchain_google_genai import GoogleGenerativeAI from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser # Type Hinting from typing import Annotated, AsyncIterator from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from weaviate import WeaviateClient from weaviate.collections.classes.internal import QueryReturn, Object, ReturnProperties # Secret Keys from dotenv import load_dotenv load_dotenv() # --------------------------------------------------------------------- # # -- Constants -- # ROOT = os.path.dirname(os.path.dirname(__file__)) GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") OPEN_AI_KEY = os.getenv("OPEN_AI_KEY") # LLM_MODEL_NAME = "gpt-3.5-turbo-0125" LLM_MODEL_NAME = "models/gemini-1.5-pro" # OCR DETECTION_MODEL = "db_mobilenet_v3_large" RECOGNITION_MODEL = "crnn_mobilenet_v3_large" # Document Load CHUNK_SIZE = 128 CHUNK_OVERLAP = 32 MD_SEPARATORS = [ # First, try to split along Markdown headings (starting with level 2) "\n#{1,6} ", # Note the alternative syntax for headings (below) is not handled here # Heading level 2 # --------------- # End of code block "```\n", # Horizontal lines "\n\\*\\*\\*+\n", "\n---+\n", "\n___+\n", # Note that this splitter doesn't handle horizontal lines defined # by *three or more* of ***, ---, or ___, but this is not handled "\n\n", r"(?<=\w{2}\.\s)", "\n", " ", "", ] SEPARATORS = [r"(?<=\w{2}\.\s)", "\n"] ENCODING_NAME = "cl100k_base" # Auto Merging L1 = 4 L2 = 16 # Retrieving Filters SORT = Sort.by_property(name="index", ascending=True) # Embedding Model EMBEDDING_MODEL_NAME = "Alibaba-NLP/gte-base-en-v1.5" RETRIEVAL_PROMPT = "Represent this sentence for searching relevant passages: " # Re-ranker Model # RERANKER_MODEL_NAME = "mixedbread-ai/mxbai-rerank-large-v1" RERANKER_MODEL_NAME = "jinaai/jina-reranker-v1-turbo-en" # Database Name DB_NAME = "bookipedia" # TTS Model Paths PIPER_MODEL_PATH = os.path.join(ROOT, "models/[model_name.onnx]") PIPER_CONFIG_PATH = PIPER_MODEL_PATH + ".json" # Back-End URLs BACKEND_URL = "[URL to Backend API]" # FILE_URL = BACKEND_URL + "file/" CHAT_SUMMARY_URL = BACKEND_URL + "chat-summary/" POST_HOCR_URL = BACKEND_URL + "ocr-file/" ACKNOWLEDGE_URL = BACKEND_URL + "ai-applied/" # RAG SUMMARY_TOKEN_LIMIT = 8064 FETCHING_LIMIT = 1024 # --------------------------------------------------------------------- #
4,087
Python
.py
110
32.009091
88
0.656409
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,395
root_config.py
yousefmrashad_bookipedia/utils/root_config.py
# -- Setup directory for utils package -- # import sys, os root_path = os.path.dirname(os.path.dirname(__file__)) sys.path.append(root_path) # =================================================== #
200
Python
.py
5
38.4
55
0.505102
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,396
font.py
yousefmrashad_bookipedia/utils/font.py
# SPDX-FileCopyrightText: 2023 James R. Barlow # SPDX-License-Identifier: MPL-2.0 from __future__ import annotations import logging import unicodedata import zlib import os from pikepdf import ( Dictionary, Name, Pdf, ) from pikepdf.canvas import Font log = logging.getLogger(__name__) class EncodableFont(Font): def text_encode(self, text: str) -> bytes: raise NotImplementedError() data_path = os.path.dirname(__file__) class GlyphlessFont(EncodableFont): CID_TO_GID_DATA = zlib.compress(b"\x00\x01" * 65536) GLYPHLESS_FONT_NAME = 'pdf.ttf' GLYPHLESS_FONT_PATH = os.path.join(data_path, GLYPHLESS_FONT_NAME) with open(GLYPHLESS_FONT_PATH, 'rb') as font_file: GLYPHLESS_FONT = font_file.read() CHAR_ASPECT = 2 def __init__(self): pass def text_width(self, text: str, fontsize: float) -> float: """Estimate the width of a text string when rendered with the given font.""" # NFKC: split ligatures, combine diacritics return len(unicodedata.normalize("NFKC", text)) * (fontsize / self.CHAR_ASPECT) def text_encode(self, text: str) -> bytes: return text.encode('utf-16be') def register(self, pdf: Pdf): """Register the glyphless font. Create several data structures in the Pdf to describe the font. While it create the data, a reference should be set in at least one page's /Resources dictionary to retain the font in the output PDF and ensure it is usable on that page. """ PLACEHOLDER = Name.Placeholder basefont = pdf.make_indirect( Dictionary( BaseFont=Name.GlyphLessFont, DescendantFonts=[PLACEHOLDER], Encoding=Name("/Identity-H"), Subtype=Name.Type0, ToUnicode=PLACEHOLDER, Type=Name.Font, ) ) cid_font_type2 = pdf.make_indirect( Dictionary( BaseFont=Name.GlyphLessFont, CIDToGIDMap=PLACEHOLDER, CIDSystemInfo=Dictionary( Ordering="Identity", Registry="Adobe", Supplement=0, ), FontDescriptor=PLACEHOLDER, Subtype=Name.CIDFontType2, Type=Name.Font, DW=1000 // self.CHAR_ASPECT, ) ) basefont.DescendantFonts = [cid_font_type2] cid_font_type2.CIDToGIDMap = pdf.make_stream( self.CID_TO_GID_DATA, Filter=Name.FlateDecode ) basefont.ToUnicode = pdf.make_stream( b"/CIDInit /ProcSet findresource begin\n" b"12 dict begin\n" b"begincmap\n" b"/CIDSystemInfo\n" b"<<\n" b" /Registry (Adobe)\n" b" /Ordering (UCS)\n" b" /Supplement 0\n" b">> def\n" b"/CMapName /Adobe-Identify-UCS def\n" b"/CMapType 2 def\n" b"1 begincodespacerange\n" b"<0000> <FFFF>\n" b"endcodespacerange\n" b"1 beginbfrange\n" b"<0000> <FFFF> <0000>\n" b"endbfrange\n" b"endcmap\n" b"CMapName currentdict /CMap defineresource pop\n" b"end\n" b"end\n" ) font_descriptor = pdf.make_indirect( Dictionary( Ascent=1000, CapHeight=1000, Descent=-1, Flags=5, # Fixed pitch and symbolic FontBBox=[0, 0, 1000 // self.CHAR_ASPECT, 1000], FontFile2=PLACEHOLDER, FontName=Name.GlyphLessFont, ItalicAngle=0, StemV=80, Type=Name.FontDescriptor, ) ) font_descriptor.FontFile2 = pdf.make_stream(self.GLYPHLESS_FONT) cid_font_type2.FontDescriptor = font_descriptor return basefont class Courier(EncodableFont): """Courier font.""" def text_width(self, text: str, fontsize: float) -> float: """Estimate the width of a text string when rendered with the given font.""" return len(text) * fontsize def text_encode(self, text: str) -> bytes: return text.encode('pdfdoc', errors='ignore') def register(self, pdf: Pdf) -> Dictionary: """Register the font.""" return pdf.make_indirect( Dictionary( BaseFont=Name.Courier, Type=Name.Font, Subtype=Name.Type1, ) )
4,754
Python
.py
125
26.256
89
0.55587
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,397
functions.py
yousefmrashad_bookipedia/utils/functions.py
# Config from root_config import * from utils.config import * # ===================================================================== # # -- Helpers -- # # OCR def map_values(img, in_min, in_max, out_min, out_max): return (img - in_min) * ((out_max - out_min) / (in_max - in_min)) + out_min # --------------------------------------------------------------------- # # Document Loader def count_tokens(text: str) -> int: encoding = tiktoken.get_encoding(encoding_name=ENCODING_NAME) return len(encoding.encode(text)) # --------------------------------------------------------------------- # # Retrieving Filters def id_filter(source_id: str): return wvc.query.Filter.by_property("source_id").equal(source_id) def ids_filter(source_ids: list[str]): return wvc.query.Filter.by_property("source_id").contains_any(source_ids) def page_filter(page_no: int): return wvc.query.Filter.by_property("page_no").equal(page_no) # --------------------------------------------------------------------- # def merge_chunks(chunks: list[str]) -> str: if not chunks: return "" # Return empty string if there are no chunks merged_text = chunks[0] # Initialize merged text with the first chunk for chunk in chunks[1:]: if not chunk: # Skip empty chunks continue overlap = find_overlap(merged_text, chunk) if overlap > 0: # Ensure overlap is valid merged_text += chunk[overlap:] else: merged_text += " " + chunk # If no overlap, append the entire chunk return merged_text # --------------------------------------------------------------------- # def find_overlap(text1: str, text2: str) -> int: if not text1 or not text2: return 0 # Return 0 if any input string is empty n = len(text1) m = len(text2) overlap = [0] * m j = 0 for i in range(1, m): while j > 0 and text2[i] != text2[j]: j = overlap[j - 1] if text2[i] == text2[j]: j += 1 overlap[i] = j j = 0 for i in range(n): while j > 0 and text1[i] != text2[j]: j = overlap[j - 1] if text1[i] == text2[j]: j += 1 if j == m: return m return j # --------------------------------------------------------------------- # def calculate_imagebox_percentage(doc: fitz.Document) -> float: total_imagebox_area = 0 total_page_area = 0 for page in doc: imagebox_area = 0 page_area = page.rect.height * page.rect.width total_page_area += page_area for image in page.get_image_info(): imagebox = image['bbox'] imagebox_area += (imagebox[2] - imagebox[0]) * (imagebox[3] - imagebox[1]) total_imagebox_area += imagebox_area return (total_imagebox_area / total_page_area) # --------------------------------------------------------------------- #
3,035
Python
.py
72
34.597222
87
0.487989
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,398
db_config.py
yousefmrashad_bookipedia/utils/db_config.py
# Config from root_config import * from utils.config import * # ================================================== # class DB: def __init__(self): self.client = weaviate.connect_to_local() def connect(self): if not (self.client.collections.exists(DB_NAME)): self.create() return self.client def create(self): self.client.collections.create(name=DB_NAME, vectorizer_config=wvc.config.Configure.Vectorizer.none(), vector_index_config=wvc.config.Configure.VectorIndex.hnsw(distance_metric=wvc.config.VectorDistances.COSINE), properties = [ wvc.config.Property(name="index", data_type=wvc.config.DataType.INT, vectorize_property_name=False), wvc.config.Property(name="source_id", data_type=wvc.config.DataType.TEXT, vectorize_property_name=False), wvc.config.Property(name="page_no", data_type=wvc.config.DataType.INT, vectorize_property_name=False), wvc.config.Property(name="text", data_type=wvc.config.DataType.TEXT, vectorize_property_name=False, tokenization=wvc.config.Tokenization.LOWERCASE), wvc.config.Property(name="l1", data_type=wvc.config.DataType.INT, vectorize_property_name=False), wvc.config.Property(name="l2", data_type=wvc.config.DataType.INT, vectorize_property_name=False), ]) # -------------------------------------------------- #
1,506
Python
.py
24
51.083333
165
0.619738
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)
2,286,399
hocr.py
yousefmrashad_bookipedia/utils/hocr.py
# SPDX-FileCopyrightText: 2010 Jonathan Brinley # SPDX-FileCopyrightText: 2013-2014 Julien Pfefferkorn # SPDX-FileCopyrightText: 2023 James R. Barlow # SPDX-License-Identifier: MIT """hOCR transform implementation.""" from __future__ import annotations import logging import os import re import unicodedata from dataclasses import dataclass from itertools import pairwise from math import atan, cos, pi from pathlib import Path from defusedxml import ElementTree from pikepdf import Matrix, Name, Rectangle, Pdf from pikepdf.canvas import ( BLACK, BLUE, CYAN, DARKGREEN, GREEN, MAGENTA, RED, Canvas, Text, TextDirection, ) from utils.font import EncodableFont as Font from utils.font import GlyphlessFont log = logging.getLogger(__name__) INCH = 72.0 Element = ElementTree.Element @dataclass class DebugRenderOptions: """A class for managing rendering options.""" render_paragraph_bbox: bool = False render_baseline: bool = False render_triangle: bool = False render_line_bbox: bool = False render_word_bbox: bool = False render_space_bbox: bool = False class HocrTransformError(Exception): """Error while applying hOCR transform.""" class HocrTransform: """A class for converting documents from the hOCR format. For details of the hOCR format, see: http://kba.cloud/hocr-spec/. """ box_pattern = re.compile(r'bbox\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)') baseline_pattern = re.compile( r''' baseline \s+ ([\-\+]?\d*\.?\d*) \s+ # +/- decimal float ([\-\+]?\d+) # +/- int''', re.VERBOSE, ) def __init__( self, *, hocr: ElementTree.Element | str | Path = None, dpi: float, debug: bool = False, fontname: Name = Name("/f-0-0"), font: Font = GlyphlessFont(), debug_render_options: DebugRenderOptions | None = None, ): """Initialize the HocrTransform object.""" if debug: log.warning("Use debug_render_options instead", DeprecationWarning) self.render_options = DebugRenderOptions( render_baseline=debug, render_triangle=debug, render_line_bbox=False, render_word_bbox=debug, render_paragraph_bbox=False, render_space_bbox=False, ) else: self.render_options = debug_render_options or DebugRenderOptions() self.dpi = dpi if isinstance(hocr, ElementTree.ElementTree): self.hocr = hocr else: self.hocr = ElementTree.parse(os.fspath(hocr)) self._fontname = fontname self._font = font # if the hOCR file has a namespace, ElementTree requires its use to # find elements matches = re.match(r'({.*})html', self.hocr.getroot().tag) self.xmlns = '' if matches: self.xmlns = matches.group(1) for div in self.hocr.findall(self._child_xpath('div', 'ocr_page')): coords = self.element_coordinates(div) if not coords: raise HocrTransformError("hocr file is missing page dimensions") self.width = (coords.urx - coords.llx) / (self.dpi / INCH) self.height = (coords.ury - coords.lly) / (self.dpi / INCH) # Stop after first div that has page coordinates break def _get_element_text(self, element: Element): """Return the textual content of the element and its children.""" text = '' if element.text is not None: text += element.text for child in element: text += self._get_element_text(child) if element.tail is not None: text += element.tail return text @classmethod def element_coordinates(cls, element: Element) -> Rectangle | None: """Get coordinates of the bounding box around an element.""" matches = cls.box_pattern.search(element.attrib.get('title', '')) if not matches: return None return Rectangle( float(matches.group(1)), # llx = left float(matches.group(2)), # lly = top float(matches.group(3)), # urx = right float(matches.group(4)), # ury = bottom ) @classmethod def baseline(cls, element: Element) -> tuple[float, float]: """Get baseline's slope and intercept.""" matches = cls.baseline_pattern.search(element.attrib.get('title', '')) if not matches: return (0.0, 0.0) return float(matches.group(1)), int(matches.group(2)) def _child_xpath(self, html_tag: str, html_class: str | None = None) -> str: xpath = f".//{self.xmlns}{html_tag}" if html_class: xpath += f"[@class='{html_class}']" return xpath @classmethod def normalize_text(cls, s: str) -> str: """Normalize the given text using the NFKC normalization form.""" return unicodedata.normalize("NFKC", s) def to_pdf( self, *, #out_filename: Path, image = None, invisible_text: bool = True, ) -> Pdf: """Creates a PDF file with an image superimposed on top of the text. Text is positioned according to the bounding box of the lines in the hOCR file. The image need not be identical to the image used to create the hOCR file. It can have a lower resolution, different color mode, etc. Arguments: out_filename: Path of PDF to write. image: Image to use for this file. If omitted, the OCR text is shown. invisible_text: If True, text is rendered invisible so that is selectable but never drawn. If False, text is visible and may be seen if the image is skipped or deleted in Acrobat. """ # create the PDF file # page size in points (1/72 in.) canvas = Canvas(page_size=(self.width, self.height)) canvas.add_font(self._fontname, self._font) page_matrix = ( Matrix() .translated(0, self.height) .scaled(1, -1) .scaled(INCH / self.dpi, INCH / self.dpi) ) log.debug(page_matrix) with canvas.do.save_state(cm=page_matrix): self._debug_draw_paragraph_boxes(canvas) found_lines = False for par in self.hocr.iterfind(self._child_xpath('p', 'ocr_par')): for line in ( element for element in par.iterfind(self._child_xpath('span')) if 'class' in element.attrib and element.attrib['class'] in {'ocr_header', 'ocr_line', 'ocr_textfloat'} ): found_lines = True direction = self._get_text_direction(par) inject_word_breaks = self._get_inject_word_breaks(par) self._do_line( canvas, line, "ocrx_word", invisible_text, direction, inject_word_breaks, ) if not found_lines: # Tesseract did not report any lines (just words) root = self.hocr.find(self._child_xpath('div', 'ocr_page')) direction = self._get_text_direction(root) self._do_line( canvas, root, "ocrx_word", invisible_text, direction, True, ) # put the image on the page, scaled to fill the page if image is not None: canvas.do.draw_image( image, 0, 0, width=self.width, height=self.height ) # finish up the page and save it return canvas.to_pdf() def _get_text_direction(self, par): """Get the text direction of the paragraph. Arabic, Hebrew, Persian, are right-to-left languages. """ return ( TextDirection.RTL if par.attrib.get('dir', 'ltr') == 'rtl' else TextDirection.LTR ) def _get_inject_word_breaks(self, par): """Determine whether word breaks should be injected. In Chinese, Japanese, and Korean, word breaks are not injected, because words are usually one or two characters and separators are usually explicit. In all other languages, we inject word breaks to help word segmentation. """ lang = par.attrib.get('lang', '') log.debug(lang) if lang in {'chi_sim', 'chi_tra', 'jpn', 'kor'}: return False return True @classmethod def polyval(cls, poly, x): # pragma: no cover """Calculate the value of a polynomial at a point.""" return x * poly[0] + poly[1] def _do_line( self, canvas: Canvas, line: Element | None, elemclass: str, invisible_text: bool, text_direction: TextDirection, inject_word_breaks: bool, ): """Render the text for a given line. The canvas's coordinate system must be configured so that hOCR pixel coordinates are mapped to PDF coordinates. """ if line is None: return line_box = self.element_coordinates(line) if not line_box: return assert line_box.ury > line_box.lly # lly is top, ury is bottom self._debug_draw_line_bbox(canvas, line_box) # Baseline is a polynomial (usually straight line) that describes the # text baseline relative to the bottom left corner of the line bounding # box. bottom_left_corner = line_box.llx, line_box.ury slope, intercept = self.baseline(line) if abs(slope) < 0.005: slope = 0.0 angle = atan(slope) # Setup a new coordinate system on the line box's intercept and rotated by # its slope. line_matrix = ( Matrix() .translated(*bottom_left_corner) .translated(0, intercept) .rotated(angle / pi * 180) ) log.debug(line_matrix) with canvas.do.save_state(cm=line_matrix): text = Text(direction=text_direction) # Don't allow the font to break out of the bounding box. Division by # cos_a accounts for extra clearance between the glyph's vertical axis # on a sloped baseline and the edge of the bounding box. line_box_height = abs(line_box.height) / cos(angle) fontsize = line_box_height + intercept text.font(self._fontname, fontsize) text.render_mode(3 if invisible_text else 0) self._debug_draw_baseline( canvas, line_matrix.inverse().transform(line_box), 0 ) canvas.do.fill_color(BLACK) # text in black elements = line.findall(self._child_xpath('span', elemclass)) for elem, next_elem in pairwise(elements + [None]): self._do_line_word( canvas, line_matrix, text, fontsize, elem, next_elem, text_direction, inject_word_breaks, ) canvas.do.draw_text(text) def _do_line_word( self, canvas: Canvas, line_matrix: Matrix, text: Text, fontsize: float, elem: Element, next_elem: Element | None, text_direction: TextDirection, inject_word_breaks: bool, ): """Render the text for a single word.""" if elem is None: return elemtxt = self.normalize_text(self._get_element_text(elem).strip()) if elemtxt == '': return hocr_box = self.element_coordinates(elem) if hocr_box is None: return box = line_matrix.inverse().transform(hocr_box) font_width = self._font.text_width(elemtxt, fontsize) # Debug sketches self._debug_draw_word_triangle(canvas, box) self._debug_draw_word_bbox(canvas, box) # If this word is 0 units wide, our best bet seems to be to suppress this text if text_direction == TextDirection.RTL: log.info("RTL: %s", elemtxt) if font_width > 0: if text_direction == TextDirection.LTR: text.text_transform(Matrix(1, 0, 0, -1, box.llx, 0)) elif text_direction == TextDirection.RTL: text.text_transform(Matrix(-1, 0, 0, -1, box.llx + box.width, 0)) text.horiz_scale(100 * box.width / font_width) if next_elem is None: elemtxt = elemtxt = elemtxt + '\n' text.show(self._font.text_encode(elemtxt)) # Get coordinates of the next word (if there is one) hocr_next_box = ( self.element_coordinates(next_elem) if next_elem is not None else None ) if hocr_next_box is None: return # Render a space this word and the next word. The explicit space helps # PDF viewers identify the word break, and horizontally scaling it to # occupy the space the between the words helps the PDF viewer # avoid combiningthewordstogether. if not inject_word_breaks: return next_box = line_matrix.inverse().transform(hocr_next_box) if text_direction == TextDirection.LTR: space_box = Rectangle(box.urx, box.lly, next_box.llx, next_box.ury) elif text_direction == TextDirection.RTL: space_box = Rectangle(next_box.urx, box.lly, box.llx, next_box.ury) self._debug_draw_space_bbox(canvas, space_box) space_width = self._font.text_width(' ', fontsize) if space_width > 0: if text_direction == TextDirection.LTR: text.text_transform(Matrix(1, 0, 0, -1, space_box.llx, 0)) elif text_direction == TextDirection.RTL: text.text_transform( Matrix(-1, 0, 0, -1, space_box.llx + space_box.width, 0) ) text.horiz_scale(100 * space_box.width / space_width) text.show(self._font.text_encode(' ')) def _debug_draw_paragraph_boxes(self, canvas: Canvas, color=CYAN): """Draw boxes around paragraphs in the document.""" if not self.render_options.render_paragraph_bbox: # pragma: no cover return with canvas.do.save_state(): # draw box around paragraph canvas.do.stroke_color(color).line_width(0.1) for elem in self.hocr.iterfind(self._child_xpath('p', 'ocr_par')): elemtxt = self._get_element_text(elem).strip() if len(elemtxt) == 0: continue ocr_par = self.element_coordinates(elem) if ocr_par is None: continue canvas.do.rect( ocr_par.llx, ocr_par.lly, ocr_par.width, ocr_par.height, fill=0 ) def _debug_draw_line_bbox(self, canvas: Canvas, line_box: Rectangle, color=BLUE): """Render the bounding box of a text line.""" if not self.render_options.render_line_bbox: # pragma: no cover return with canvas.do.save_state(): canvas.do.stroke_color(color).line_width(0.15).rect( line_box.llx, line_box.lly, line_box.width, line_box.height, fill=0 ) def _debug_draw_word_triangle( self, canvas: Canvas, box: Rectangle, color=RED, line_width=0.1 ): """Render a triangle that conveys word height and drawing direction.""" if not self.render_options.render_triangle: # pragma: no cover return with canvas.do.save_state(): canvas.do.stroke_color(color).line_width(line_width).line( box.llx, box.lly, box.urx, box.lly ).line(box.urx, box.lly, box.llx, box.ury).line( box.llx, box.lly, box.llx, box.ury ) def _debug_draw_word_bbox( self, canvas: Canvas, box: Rectangle, color=GREEN, line_width=0.1 ): """Render a box depicting the word.""" if not self.render_options.render_word_bbox: # pragma: no cover return with canvas.do.save_state(): canvas.do.stroke_color(color).line_width(line_width).rect( box.llx, box.lly, box.width, box.height, fill=0 ) def _debug_draw_space_bbox( self, canvas: Canvas, box: Rectangle, color=DARKGREEN, line_width=0.1 ): """Render a box depicting the space between two words.""" if not self.render_options.render_space_bbox: # pragma: no cover return with canvas.do.save_state(): canvas.do.fill_color(color).line_width(line_width).rect( box.llx, box.lly, box.width, box.height, fill=1 ) def _debug_draw_baseline( self, canvas: Canvas, line_box: Rectangle, baseline_lly, color=MAGENTA, line_width=0.25, ): """Render the text baseline.""" if not self.render_options.render_baseline: return with canvas.do.save_state(): canvas.do.stroke_color(color).line_width(line_width).line( line_box.llx, baseline_lly, line_box.urx, baseline_lly, )
18,360
Python
.py
439
29.904328
87
0.559555
yousefmrashad/bookipedia
8
2
0
GPL-3.0
9/5/2024, 10:48:01 PM (Europe/Amsterdam)