Commit 0bdf8214 authored by aniket-engg's avatar aniket-engg

libs linting fix

parent 2e6d289a
...@@ -2,7 +2,9 @@ ...@@ -2,7 +2,9 @@
"extends": "../../.eslintrc", "extends": "../../.eslintrc",
"rules": { "rules": {
"@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off" "@typescript-eslint/no-unused-vars": "off",
"no-unused-vars": "off",
"dot-notation": "off"
}, },
"ignorePatterns": ["!**/*"] "ignorePatterns": ["!**/*"]
} }
export { default as CodeAnalysis} from './solidity-analyzer' export { default as CodeAnalysis } from './solidity-analyzer'
...@@ -9,7 +9,6 @@ type ModuleObj = { ...@@ -9,7 +9,6 @@ type ModuleObj = {
} }
export default class staticAnalysisRunner { export default class staticAnalysisRunner {
/** /**
* Run analysis (Used by IDE) * Run analysis (Used by IDE)
* @param compilationResult contract compilation result * @param compilationResult contract compilation result
...@@ -18,9 +17,9 @@ export default class staticAnalysisRunner { ...@@ -18,9 +17,9 @@ export default class staticAnalysisRunner {
*/ */
run (compilationResult: CompilationResult, toRun: number[], callback: ((reports: AnalysisReport[]) => void)): void { run (compilationResult: CompilationResult, toRun: number[], callback: ((reports: AnalysisReport[]) => void)): void {
const modules: ModuleObj[] = toRun.map((i) => { const modules: ModuleObj[] = toRun.map((i) => {
const module = this.modules()[i] const Module = this.modules()[i]
const m = new module() const m = new Module()
return { 'name': m.name, 'mod': m } return { name: m.name, mod: m }
}) })
this.runWithModuleList(compilationResult, modules, callback) this.runWithModuleList(compilationResult, modules, callback)
} }
...@@ -36,21 +35,21 @@ export default class staticAnalysisRunner { ...@@ -36,21 +35,21 @@ export default class staticAnalysisRunner {
// Also provide convenience analysis via the AST walker. // Also provide convenience analysis via the AST walker.
const walker = new AstWalker() const walker = new AstWalker()
for (const k in compilationResult.sources) { for (const k in compilationResult.sources) {
walker.walkFull(compilationResult.sources[k].ast, walker.walkFull(compilationResult.sources[k].ast,
(node: any) => { (node: any) => {
modules.map((item: ModuleObj) => { modules.map((item: ModuleObj) => {
if (item.mod.visit !== undefined) { if (item.mod.visit !== undefined) {
try { try {
item.mod.visit(node) item.mod.visit(node)
} catch (e) { } catch (e) {
reports.push({ reports.push({
name: item.name, report: [{ warning: 'INTERNAL ERROR in module ' + item.name + ' ' + e.message, error: e.stack }] name: item.name, report: [{ warning: 'INTERNAL ERROR in module ' + item.name + ' ' + e.message, error: e.stack }]
}) })
}
} }
} })
}) return true
return true }
}
) )
} }
......
import { getStateVariableDeclarationsFromContractNode, getInheritsFromName, getContractName, import {
getFunctionOrModifierDefinitionParameterPart, getType, getDeclaredVariableName, getStateVariableDeclarationsFromContractNode, getInheritsFromName, getContractName,
getFunctionDefinitionReturnParameterPart, getCompilerVersion } from './staticAnalysisCommon' getFunctionOrModifierDefinitionParameterPart, getType, getDeclaredVariableName,
getFunctionDefinitionReturnParameterPart, getCompilerVersion
} from './staticAnalysisCommon'
import { AstWalker } from '@remix-project/remix-astwalker' import { AstWalker } from '@remix-project/remix-astwalker'
import { FunctionDefinitionAstNode, ParameterListAstNode, ModifierDefinitionAstNode, ContractHLAst, VariableDeclarationAstNode, import {
FunctionHLAst, ReportObj, ReportFunction, VisitFunction, ModifierHLAst, CompilationResult } from '../../types' FunctionDefinitionAstNode, ParameterListAstNode, ModifierDefinitionAstNode, ContractHLAst, VariableDeclarationAstNode,
FunctionHLAst, ReportObj, ReportFunction, VisitFunction, ModifierHLAst, CompilationResult
} from '../../types'
type WrapFunction = ((contracts: ContractHLAst[], isSameName: boolean, version: string) => ReportObj[]) type WrapFunction = ((contracts: ContractHLAst[], isSameName: boolean, version: string) => ReportObj[])
...@@ -23,7 +27,7 @@ export default class abstractAstView { ...@@ -23,7 +27,7 @@ export default class abstractAstView {
*/ */
multipleContractsWithSameName = false multipleContractsWithSameName = false
/** /**
* Builds a higher level AST view. I creates a list with each contract as an object in it. * Builds a higher level AST view. I creates a list with each contract as an object in it.
* Example contractsOut: * Example contractsOut:
* *
...@@ -48,9 +52,10 @@ export default class abstractAstView { ...@@ -48,9 +52,10 @@ export default class abstractAstView {
* @contractsOut {list} return list for high level AST view * @contractsOut {list} return list for high level AST view
* @return {ASTNode -> void} returns a function that can be used as visit function for static analysis modules, to build up a higher level AST view for further analysis. * @return {ASTNode -> void} returns a function that can be used as visit function for static analysis modules, to build up a higher level AST view for further analysis.
*/ */
// eslint-disable-next-line camelcase
build_visit (relevantNodeFilter: ((node:any) => boolean)): VisitFunction { build_visit (relevantNodeFilter: ((node:any) => boolean)): VisitFunction {
return (node: any) => { return (node: any) => {
if (node.nodeType === "ContractDefinition") { if (node.nodeType === 'ContractDefinition') {
this.setCurrentContract({ this.setCurrentContract({
node: node, node: node,
functions: [], functions: [],
...@@ -59,11 +64,11 @@ export default class abstractAstView { ...@@ -59,11 +64,11 @@ export default class abstractAstView {
inheritsFrom: [], inheritsFrom: [],
stateVariables: getStateVariableDeclarationsFromContractNode(node) stateVariables: getStateVariableDeclarationsFromContractNode(node)
}) })
} else if (node.nodeType === "InheritanceSpecifier") { } else if (node.nodeType === 'InheritanceSpecifier') {
const currentContract: ContractHLAst = this.getCurrentContract() const currentContract: ContractHLAst = this.getCurrentContract()
const inheritsFromName: string = getInheritsFromName(node) const inheritsFromName: string = getInheritsFromName(node)
currentContract.inheritsFrom.push(inheritsFromName) currentContract.inheritsFrom.push(inheritsFromName)
} else if (node.nodeType === "FunctionDefinition") { } else if (node.nodeType === 'FunctionDefinition') {
this.setCurrentFunction({ this.setCurrentFunction({
node: node, node: node,
relevantNodes: [], relevantNodes: [],
...@@ -78,14 +83,14 @@ export default class abstractAstView { ...@@ -78,14 +83,14 @@ export default class abstractAstView {
this.getCurrentFunction().relevantNodes.push(item.node) this.getCurrentFunction().relevantNodes.push(item.node)
} }
}) })
} else if (node.nodeType === "ModifierDefinition") { } else if (node.nodeType === 'ModifierDefinition') {
this.setCurrentModifier({ this.setCurrentModifier({
node: node, node: node,
relevantNodes: [], relevantNodes: [],
localVariables: this.getLocalVariables(node), localVariables: this.getLocalVariables(node),
parameters: this.getLocalParameters(node) parameters: this.getLocalParameters(node)
}) })
} else if (node.nodeType === "ModifierInvocation") { } else if (node.nodeType === 'ModifierInvocation') {
if (!this.isFunctionNotModifier) throw new Error('abstractAstView.js: Found modifier invocation outside of function scope.') if (!this.isFunctionNotModifier) throw new Error('abstractAstView.js: Found modifier invocation outside of function scope.')
this.getCurrentFunction().modifierInvocations.push(node) this.getCurrentFunction().modifierInvocations.push(node)
} else if (relevantNodeFilter(node)) { } else if (relevantNodeFilter(node)) {
...@@ -102,6 +107,7 @@ export default class abstractAstView { ...@@ -102,6 +107,7 @@ export default class abstractAstView {
} }
} }
// eslint-disable-next-line camelcase
build_report (wrap: WrapFunction): ReportFunction { build_report (wrap: WrapFunction): ReportFunction {
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
return (compilationResult: CompilationResult) => { return (compilationResult: CompilationResult) => {
...@@ -176,7 +182,7 @@ export default class abstractAstView { ...@@ -176,7 +182,7 @@ export default class abstractAstView {
private getLocalVariables (funcNode: ParameterListAstNode): VariableDeclarationAstNode[] { private getLocalVariables (funcNode: ParameterListAstNode): VariableDeclarationAstNode[] {
const locals: VariableDeclarationAstNode[] = [] const locals: VariableDeclarationAstNode[] = []
new AstWalker().walkFull(funcNode, (node: any) => { new AstWalker().walkFull(funcNode, (node: any) => {
if (node.nodeType === "VariableDeclaration") locals.push(node) if (node.nodeType === 'VariableDeclaration') locals.push(node)
return true return true
}) })
return locals return locals
......
import { default as category } from './categories' import category from './categories'
import { isSubScopeWithTopLevelUnAssignedBinOp, getUnAssignedTopLevelBinOps } from './staticAnalysisCommon' import { isSubScopeWithTopLevelUnAssignedBinOp, getUnAssignedTopLevelBinOps } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, BlockAstNode, IfStatementAstNode, import {
WhileStatementAstNode, ForStatementAstNode, CompilationResult, ExpressionStatementAstNode, SupportedVersion} from './../../types' AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, BlockAstNode, IfStatementAstNode,
WhileStatementAstNode, ForStatementAstNode, CompilationResult, ExpressionStatementAstNode, SupportedVersion
} from './../../types'
export default class assignAndCompare implements AnalyzerModule { export default class assignAndCompare implements AnalyzerModule {
warningNodes: ExpressionStatementAstNode[] = [] warningNodes: ExpressionStatementAstNode[] = []
name = `Result not used: ` name = 'Result not used: '
description = `The result of an operation not used` description = 'The result of an operation not used'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
......
import { default as category } from './categories' import category from './categories'
import { isBlockBlockHashAccess } from './staticAnalysisCommon' import { isBlockBlockHashAccess } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion } from './../../types'
export default class blockBlockhash implements AnalyzerModule { export default class blockBlockhash implements AnalyzerModule {
warningNodes: FunctionCallAstNode[] = [] warningNodes: FunctionCallAstNode[] = []
name = `Block hash: ` name = 'Block hash: '
description = `Can be influenced by miners` description = 'Can be influenced by miners'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -30,4 +30,3 @@ export default class blockBlockhash implements AnalyzerModule { ...@@ -30,4 +30,3 @@ export default class blockBlockhash implements AnalyzerModule {
}) })
} }
} }
import { default as category } from './categories' import category from './categories'
import { isNowAccess, isBlockTimestampAccess, getCompilerVersion } from './staticAnalysisCommon' import { isNowAccess, isBlockTimestampAccess, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, IdentifierAstNode, import {
MemberAccessAstNode, SupportedVersion} from './../../types' AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, IdentifierAstNode,
MemberAccessAstNode, SupportedVersion
} from './../../types'
export default class blockTimestamp implements AnalyzerModule { export default class blockTimestamp implements AnalyzerModule {
warningNowNodes: IdentifierAstNode[] = [] warningNowNodes: IdentifierAstNode[] = []
warningblockTimestampNodes: MemberAccessAstNode[] = [] warningblockTimestampNodes: MemberAccessAstNode[] = []
name = `Block timestamp: ` name = 'Block timestamp: '
description = `Can be influenced by miners` description = 'Can be influenced by miners'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
start: '0.4.12' start: '0.4.12'
} }
visit (node: IdentifierAstNode | MemberAccessAstNode ): void { visit (node: IdentifierAstNode | MemberAccessAstNode): void {
if (node.nodeType === "Identifier" && isNowAccess(node)) this.warningNowNodes.push(node) if (node.nodeType === 'Identifier' && isNowAccess(node)) this.warningNowNodes.push(node)
else if (node.nodeType === "MemberAccess" && isBlockTimestampAccess(node)) this.warningblockTimestampNodes.push(node) else if (node.nodeType === 'MemberAccess' && isBlockTimestampAccess(node)) this.warningblockTimestampNodes.push(node)
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
......
export default { export default {
SECURITY: {displayName: 'Security', id: 'SEC'}, SECURITY: { displayName: 'Security', id: 'SEC' },
GAS: {displayName: 'Gas & Economy', id: 'GAS'}, GAS: { displayName: 'Gas & Economy', id: 'GAS' },
MISC: {displayName: 'Miscellaneous', id: 'MISC'}, MISC: { displayName: 'Miscellaneous', id: 'MISC' },
ERC: {displayName: 'ERC', id: 'ERC'} ERC: { displayName: 'ERC', id: 'ERC' }
} }
import { default as category } from './categories' import category from './categories'
import { isInteraction, isEffect, isLocalCallGraphRelevantNode, getFullQuallyfiedFuncDefinitionIdent, import {
isWriteOnStateVariable, isStorageVariableDeclaration, getFullQualifiedFunctionCallIdent, getCompilerVersion } from './staticAnalysisCommon' isInteraction, isEffect, isLocalCallGraphRelevantNode, getFullQuallyfiedFuncDefinitionIdent,
import { default as algorithm } from './algorithmCategories' isWriteOnStateVariable, isStorageVariableDeclaration, getFullQualifiedFunctionCallIdent, getCompilerVersion
} from './staticAnalysisCommon'
import algorithm from './algorithmCategories'
import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph' import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph'
import AbstractAst from './abstractAstView' import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VariableDeclarationAstNode, import {
FunctionHLAst, ContractCallGraph, Context, FunctionCallAstNode, AssignmentAstNode, UnaryOperationAstNode, AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VariableDeclarationAstNode,
InlineAssemblyAstNode, ReportFunction, VisitFunction, FunctionCallGraph, SupportedVersion } from './../../types' FunctionHLAst, ContractCallGraph, Context, FunctionCallAstNode, AssignmentAstNode, UnaryOperationAstNode,
InlineAssemblyAstNode, ReportFunction, VisitFunction, FunctionCallGraph, SupportedVersion
} from './../../types'
export default class checksEffectsInteraction implements AnalyzerModule { export default class checksEffectsInteraction implements AnalyzerModule {
name = `Check-effects-interaction: ` name = 'Check-effects-interaction: '
description = `Potential reentrancy bugs` description = 'Potential reentrancy bugs'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.HEURISTIC algorithm: ModuleAlgorithm = algorithm.HEURISTIC
version: SupportedVersion = { version: SupportedVersion = {
...@@ -20,11 +24,11 @@ export default class checksEffectsInteraction implements AnalyzerModule { ...@@ -20,11 +24,11 @@ export default class checksEffectsInteraction implements AnalyzerModule {
abstractAst: AbstractAst = new AbstractAst() abstractAst: AbstractAst = new AbstractAst()
visit: VisitFunction = this.abstractAst.build_visit((node: FunctionCallAstNode | AssignmentAstNode | UnaryOperationAstNode | InlineAssemblyAstNode) => ( visit: VisitFunction = this.abstractAst.build_visit((node: FunctionCallAstNode | AssignmentAstNode | UnaryOperationAstNode | InlineAssemblyAstNode) => (
node.nodeType === 'FunctionCall' && (isInteraction(node) || isLocalCallGraphRelevantNode(node))) || node.nodeType === 'FunctionCall' && (isInteraction(node) || isLocalCallGraphRelevantNode(node))) ||
((node.nodeType === 'Assignment' || node.nodeType === 'UnaryOperation' || node.nodeType === 'InlineAssembly') && isEffect(node))) ((node.nodeType === 'Assignment' || node.nodeType === 'UnaryOperation' || node.nodeType === 'InlineAssembly') && isEffect(node)))
report: ReportFunction = this.abstractAst.build_report(this._report.bind(this)) report: ReportFunction = this.abstractAst.build_report(this._report.bind(this))
private _report (contracts: ContractHLAst[], multipleContractsWithSameName: boolean, version: string): ReportObj[] { private _report (contracts: ContractHLAst[], multipleContractsWithSameName: boolean, version: string): ReportObj[] {
const warnings: ReportObj[] = [] const warnings: ReportObj[] = []
const hasModifiers: boolean = contracts.some((item) => item.modifiers.length > 0) const hasModifiers: boolean = contracts.some((item) => item.modifiers.length > 0)
...@@ -32,16 +36,16 @@ export default class checksEffectsInteraction implements AnalyzerModule { ...@@ -32,16 +36,16 @@ export default class checksEffectsInteraction implements AnalyzerModule {
contracts.forEach((contract) => { contracts.forEach((contract) => {
contract.functions.forEach((func) => { contract.functions.forEach((func) => {
func['changesState'] = this.checkIfChangesState( func['changesState'] = this.checkIfChangesState(
getFullQuallyfiedFuncDefinitionIdent( getFullQuallyfiedFuncDefinitionIdent(
contract.node, contract.node,
func.node, func.node,
func.parameters func.parameters
), ),
this.getContext( this.getContext(
callGraph, callGraph,
contract, contract,
func) func)
) )
}) })
contract.functions.forEach((func: FunctionHLAst) => { contract.functions.forEach((func: FunctionHLAst) => {
if (this.isPotentialVulnerableFunction(func, this.getContext(callGraph, contract, func))) { if (this.isPotentialVulnerableFunction(func, this.getContext(callGraph, contract, func))) {
...@@ -50,7 +54,7 @@ export default class checksEffectsInteraction implements AnalyzerModule { ...@@ -50,7 +54,7 @@ export default class checksEffectsInteraction implements AnalyzerModule {
comments += (multipleContractsWithSameName) ? 'Note: Import aliases are currently not supported by this static analysis.' : '' comments += (multipleContractsWithSameName) ? 'Note: Import aliases are currently not supported by this static analysis.' : ''
warnings.push({ warnings.push({
warning: `Potential violation of Checks-Effects-Interaction pattern in ${funcName}: Could potentially lead to re-entrancy vulnerability. ${comments}`, warning: `Potential violation of Checks-Effects-Interaction pattern in ${funcName}: Could potentially lead to re-entrancy vulnerability. ${comments}`,
location: func.node['src'], location: func.node.src,
more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#re-entrancy` more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#re-entrancy`
}) })
} }
...@@ -92,4 +96,3 @@ export default class checksEffectsInteraction implements AnalyzerModule { ...@@ -92,4 +96,3 @@ export default class checksEffectsInteraction implements AnalyzerModule {
return analyseCallGraph(context.callGraph, startFuncName, context, (node: any, context: Context) => isWriteOnStateVariable(node, context.stateVariables)) return analyseCallGraph(context.callGraph, startFuncName, context, (node: any, context: Context) => isWriteOnStateVariable(node, context.stateVariables))
} }
} }
import { default as category } from './categories' import category from './categories'
import { isLowLevelCall, isTransfer, isExternalDirectCall, isEffect, isLocalCallGraphRelevantNode, isSelfdestructCall, import {
isDeleteUnaryOperation, isPayableFunction, isConstructor, getFullQuallyfiedFuncDefinitionIdent, hasFunctionBody, isLowLevelCall, isTransfer, isExternalDirectCall, isEffect, isLocalCallGraphRelevantNode, isSelfdestructCall,
isConstantFunction, isWriteOnStateVariable, isStorageVariableDeclaration, isCallToNonConstLocalFunction, isDeleteUnaryOperation, isPayableFunction, isConstructor, getFullQuallyfiedFuncDefinitionIdent, hasFunctionBody,
getFullQualifiedFunctionCallIdent} from './staticAnalysisCommon' isConstantFunction, isWriteOnStateVariable, isStorageVariableDeclaration, isCallToNonConstLocalFunction,
import { default as algorithm } from './algorithmCategories' getFullQualifiedFunctionCallIdent
} from './staticAnalysisCommon'
import algorithm from './algorithmCategories'
import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph' import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph'
import AbstractAst from './abstractAstView' import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractCallGraph, Context, ContractHLAst, import {
FunctionHLAst, VariableDeclarationAstNode, FunctionCallGraph, FunctionCallAstNode, VisitFunction, ReportFunction, SupportedVersion} from './../../types' AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractCallGraph, Context, ContractHLAst,
FunctionHLAst, VariableDeclarationAstNode, FunctionCallGraph, FunctionCallAstNode, VisitFunction, ReportFunction, SupportedVersion
} from './../../types'
export default class constantFunctions implements AnalyzerModule { export default class constantFunctions implements AnalyzerModule {
name = `Constant/View/Pure functions: ` name = 'Constant/View/Pure functions: '
description = `Potentially constant/view/pure functions` description = 'Potentially constant/view/pure functions'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.HEURISTIC algorithm: ModuleAlgorithm = algorithm.HEURISTIC
version: SupportedVersion = { version: SupportedVersion = {
...@@ -26,8 +30,8 @@ export default class constantFunctions implements AnalyzerModule { ...@@ -26,8 +30,8 @@ export default class constantFunctions implements AnalyzerModule {
isExternalDirectCall(node) || isExternalDirectCall(node) ||
isEffect(node) || isEffect(node) ||
isLocalCallGraphRelevantNode(node) || isLocalCallGraphRelevantNode(node) ||
node.nodeType === "InlineAssembly" || node.nodeType === 'InlineAssembly' ||
node.nodeType === "NewExpression" || node.nodeType === 'NewExpression' ||
isSelfdestructCall(node) || isSelfdestructCall(node) ||
isDeleteUnaryOperation(node) isDeleteUnaryOperation(node)
) )
...@@ -46,17 +50,17 @@ export default class constantFunctions implements AnalyzerModule { ...@@ -46,17 +50,17 @@ export default class constantFunctions implements AnalyzerModule {
func['potentiallyshouldBeConst'] = false func['potentiallyshouldBeConst'] = false
} else { } else {
func['potentiallyshouldBeConst'] = this.checkIfShouldBeConstant( func['potentiallyshouldBeConst'] = this.checkIfShouldBeConstant(
getFullQuallyfiedFuncDefinitionIdent( getFullQuallyfiedFuncDefinitionIdent(
contract.node, contract.node,
func.node, func.node,
func.parameters func.parameters
), ),
this.getContext( this.getContext(
callGraph, callGraph,
contract, contract,
func func
) )
) )
} }
}) })
contract.functions.filter((func: FunctionHLAst) => hasFunctionBody(func.node)).forEach((func: FunctionHLAst) => { contract.functions.filter((func: FunctionHLAst) => hasFunctionBody(func.node)).forEach((func: FunctionHLAst) => {
...@@ -67,13 +71,13 @@ export default class constantFunctions implements AnalyzerModule { ...@@ -67,13 +71,13 @@ export default class constantFunctions implements AnalyzerModule {
if (func['potentiallyshouldBeConst']) { if (func['potentiallyshouldBeConst']) {
warnings.push({ warnings.push({
warning: `${funcName} : Potentially should be constant/view/pure but is not. ${comments}`, warning: `${funcName} : Potentially should be constant/view/pure but is not. ${comments}`,
location: func.node['src'], location: func.node.src,
more: `https://solidity.readthedocs.io/en/${version}/contracts.html#view-functions` more: `https://solidity.readthedocs.io/en/${version}/contracts.html#view-functions`
}) })
} else { } else {
warnings.push({ warnings.push({
warning: `${funcName} : Is constant but potentially should not be. ${comments}`, warning: `${funcName} : Is constant but potentially should not be. ${comments}`,
location: func.node['src'], location: func.node.src,
more: `https://solidity.readthedocs.io/en/${version}/contracts.html#view-functions` more: `https://solidity.readthedocs.io/en/${version}/contracts.html#view-functions`
}) })
} }
...@@ -101,8 +105,8 @@ export default class constantFunctions implements AnalyzerModule { ...@@ -101,8 +105,8 @@ export default class constantFunctions implements AnalyzerModule {
isTransfer(node) || isTransfer(node) ||
this.isCallOnNonConstExternalInterfaceFunction(node, context) || this.isCallOnNonConstExternalInterfaceFunction(node, context) ||
isCallToNonConstLocalFunction(node) || isCallToNonConstLocalFunction(node) ||
node.nodeType === "InlineAssembly" || node.nodeType === 'InlineAssembly' ||
node.nodeType === "NewExpression" || node.nodeType === 'NewExpression' ||
isSelfdestructCall(node) || isSelfdestructCall(node) ||
isDeleteUnaryOperation(node) isDeleteUnaryOperation(node)
} }
......
import { default as category } from './categories' import category from './categories'
import { isDeleteOfDynamicArray, getCompilerVersion } from './staticAnalysisCommon' import { isDeleteOfDynamicArray, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion } from './../../types'
export default class deleteDynamicArrays implements AnalyzerModule { export default class deleteDynamicArrays implements AnalyzerModule {
rel: UnaryOperationAstNode[] = [] rel: UnaryOperationAstNode[] = []
name = `Delete dynamic array: ` name = 'Delete dynamic array: '
description = `Use require/assert to ensure complete deletion` description = 'Use require/assert to ensure complete deletion'
category: ModuleCategory = category.GAS category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -22,7 +22,7 @@ export default class deleteDynamicArrays implements AnalyzerModule { ...@@ -22,7 +22,7 @@ export default class deleteDynamicArrays implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts) const version = getCompilerVersion(compilationResults.contracts)
return this.rel.map((node) => { return this.rel.map((node) => {
return { return {
warning: `The "delete" operation when applied to a dynamically sized array in Solidity generates code to delete each of the elements contained. If the array is large, this operation can surpass the block gas limit and raise an OOG exception. Also nested dynamically sized objects can produce the same results.`, warning: 'The "delete" operation when applied to a dynamically sized array in Solidity generates code to delete each of the elements contained. If the array is large, this operation can surpass the block gas limit and raise an OOG exception. Also nested dynamically sized objects can produce the same results.',
location: node.src, location: node.src,
more: `https://solidity.readthedocs.io/en/${version}/types.html#delete` more: `https://solidity.readthedocs.io/en/${version}/types.html#delete`
} }
......
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { isDeleteFromDynamicArray, isMappingIndexAccess } from './staticAnalysisCommon' import { isDeleteFromDynamicArray, isMappingIndexAccess } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion } from './../../types'
export default class deleteFromDynamicArray implements AnalyzerModule { export default class deleteFromDynamicArray implements AnalyzerModule {
relevantNodes: UnaryOperationAstNode[] = [] relevantNodes: UnaryOperationAstNode[] = []
name = `Delete from dynamic array: ` name = 'Delete from dynamic array: '
description = `'delete' leaves a gap in array` description = '\'delete\' leaves a gap in array'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -21,7 +21,7 @@ export default class deleteFromDynamicArray implements AnalyzerModule { ...@@ -21,7 +21,7 @@ export default class deleteFromDynamicArray implements AnalyzerModule {
report (compilationResults: CompilationResult): ReportObj[] { report (compilationResults: CompilationResult): ReportObj[] {
return this.relevantNodes.map((node) => { return this.relevantNodes.map((node) => {
return { return {
warning: `Using "delete" on an array leaves a gap. The length of the array remains the same. If you want to remove the empty position you need to shift items manually and update the "length" property.`, warning: 'Using "delete" on an array leaves a gap. The length of the array remains the same. If you want to remove the empty position you need to shift items manually and update the "length" property.',
location: node.src, location: node.src,
more: 'https://github.com/miguelmota/solidity-idiosyncrasies#examples' more: 'https://github.com/miguelmota/solidity-idiosyncrasies#examples'
} }
......
import { default as category } from './categories' import category from './categories'
import { getFunctionDefinitionName, helpers, getDeclaredVariableName, getDeclaredVariableType } from './staticAnalysisCommon' import { getFunctionDefinitionName, helpers, getDeclaredVariableName, getDeclaredVariableType } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView' import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, VisitFunction, ReportFunction, ContractHLAst, import {
FunctionHLAst, VariableDeclarationAstNode, SupportedVersion} from './../../types' AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, VisitFunction, ReportFunction, ContractHLAst,
FunctionHLAst, VariableDeclarationAstNode, SupportedVersion
} from './../../types'
export default class erc20Decimals implements AnalyzerModule { export default class erc20Decimals implements AnalyzerModule {
name = `ERC20: ` name = 'ERC20: '
description = `'decimals' should be 'uint8'` description = '\'decimals\' should be \'uint8\''
category: ModuleCategory = category.ERC category: ModuleCategory = category.ERC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -34,11 +36,11 @@ export default class erc20Decimals implements AnalyzerModule { ...@@ -34,11 +36,11 @@ export default class erc20Decimals implements AnalyzerModule {
(f.returns.length === 0 || f.returns.length > 1) || (f.returns.length === 0 || f.returns.length > 1) ||
(f.returns.length === 1 && (f.returns[0].type !== 'uint8' || f.node.visibility !== 'public')) (f.returns.length === 1 && (f.returns[0].type !== 'uint8' || f.node.visibility !== 'public'))
) )
) )
if (decimalsVar.length > 0) { if (decimalsVar.length > 0) {
for (const node of decimalsVar) { for (const node of decimalsVar) {
warnings.push({ warnings.push({
warning: `ERC20 contract's "decimals" variable should be "uint8" type`, warning: 'ERC20 contract\'s "decimals" variable should be "uint8" type',
location: node.src, location: node.src,
more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals' more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals'
}) })
...@@ -46,7 +48,7 @@ export default class erc20Decimals implements AnalyzerModule { ...@@ -46,7 +48,7 @@ export default class erc20Decimals implements AnalyzerModule {
} else if (decimalsFun.length > 0) { } else if (decimalsFun.length > 0) {
for (const fn of decimalsFun) { for (const fn of decimalsFun) {
warnings.push({ warnings.push({
warning: `ERC20 contract's "decimals" function should have "uint8" as return type`, warning: 'ERC20 contract\'s "decimals" function should have "uint8" as return type',
location: fn.node.src, location: fn.node.src,
more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals' more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals'
}) })
...@@ -66,4 +68,3 @@ export default class erc20Decimals implements AnalyzerModule { ...@@ -66,4 +68,3 @@ export default class erc20Decimals implements AnalyzerModule {
funSignatures.includes('allowance(address,address)') funSignatures.includes('allowance(address,address)')
} }
} }
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { isLoop, isTransfer, getCompilerVersion } from './staticAnalysisCommon' import { isLoop, isTransfer, getCompilerVersion } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, import {
WhileStatementAstNode, ExpressionStatementAstNode, SupportedVersion} from './../../types' AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode,
WhileStatementAstNode, ExpressionStatementAstNode, SupportedVersion
} from './../../types'
export default class etherTransferInLoop implements AnalyzerModule { export default class etherTransferInLoop implements AnalyzerModule {
relevantNodes: ExpressionStatementAstNode[] = [] relevantNodes: ExpressionStatementAstNode[] = []
name = `Ether transfer in loop: ` name = 'Ether transfer in loop: '
description = `Transferring Ether in a for/while/do-while loop` description = 'Transferring Ether in a for/while/do-while loop'
category: ModuleCategory = category.GAS category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
start: '0.4.12' start: '0.4.12'
} }
visit (node: ForStatementAstNode | WhileStatementAstNode): void { visit (node: ForStatementAstNode | WhileStatementAstNode): void {
let transferNodes: ExpressionStatementAstNode[] = [] let transferNodes: ExpressionStatementAstNode[] = []
if(isLoop(node)) { if (isLoop(node)) {
if(node.body && node.body.nodeType === 'Block') if (node.body && node.body.nodeType === 'Block') {
transferNodes = node.body.statements.filter(child => ( child.nodeType === 'ExpressionStatement' && transferNodes = node.body.statements.filter(child =>
child.expression.nodeType === 'FunctionCall' && isTransfer(child.expression.expression))) (child.nodeType === 'ExpressionStatement' &&
// When loop body is described without braces child.expression.nodeType === 'FunctionCall' &&
else if(node.body && node.body.nodeType === 'ExpressionStatement' && node.body.expression.nodeType === 'FunctionCall' && isTransfer(node.body.expression.expression)) isTransfer(child.expression.expression)))
transferNodes.push(node.body) } else if (node.body && node.body.nodeType === 'ExpressionStatement' && node.body.expression.nodeType === 'FunctionCall' && isTransfer(node.body.expression.expression)) { transferNodes.push(node.body) }
if (transferNodes.length > 0) { // When loop body is described without braces
this.relevantNodes.push(...transferNodes) if (transferNodes.length > 0) {
} this.relevantNodes.push(...transferNodes)
} }
}
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
report (compilationResults: CompilationResult): ReportObj[] { report (compilationResults: CompilationResult): ReportObj[] {
const version = getCompilerVersion(compilationResults.contracts) const version = getCompilerVersion(compilationResults.contracts)
return this.relevantNodes.map((node) => { return this.relevantNodes.map((node) => {
return { return {
warning: `Ether payout should not be done in a loop: Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. If required then make sure that number of iterations are low and you trust each address involved.`, warning: 'Ether payout should not be done in a loop: Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. If required then make sure that number of iterations are low and you trust each address involved.',
location: node.src, location: node.src,
more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops` more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops`
} }
......
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { isDynamicArrayLengthAccess, getCompilerVersion } from './staticAnalysisCommon' import { isDynamicArrayLengthAccess, getCompilerVersion } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, SupportedVersion } from './../../types'
export default class forLoopIteratesOverDynamicArray implements AnalyzerModule { export default class forLoopIteratesOverDynamicArray implements AnalyzerModule {
relevantNodes: ForStatementAstNode[] = [] relevantNodes: ForStatementAstNode[] = []
name = `For loop over dynamic array: ` name = 'For loop over dynamic array: '
description = `Iterations depend on dynamic array's size` description = 'Iterations depend on dynamic array\'s size'
category: ModuleCategory = category.GAS category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -14,21 +14,21 @@ export default class forLoopIteratesOverDynamicArray implements AnalyzerModule { ...@@ -14,21 +14,21 @@ export default class forLoopIteratesOverDynamicArray implements AnalyzerModule {
} }
visit (node: ForStatementAstNode): void { visit (node: ForStatementAstNode): void {
const { condition } = node const { condition } = node
// Check if condition is `i < array.length - 1` // Check if condition is `i < array.length - 1`
if ((condition && condition.nodeType === "BinaryOperation" && condition.rightExpression.nodeType === "BinaryOperation" && isDynamicArrayLengthAccess(condition.rightExpression.leftExpression)) || if ((condition && condition.nodeType === 'BinaryOperation' && condition.rightExpression.nodeType === 'BinaryOperation' && isDynamicArrayLengthAccess(condition.rightExpression.leftExpression)) ||
// or condition is `i < array.length` // or condition is `i < array.length`
(condition && condition.nodeType === "BinaryOperation" && isDynamicArrayLengthAccess(condition.rightExpression))) { (condition && condition.nodeType === 'BinaryOperation' && isDynamicArrayLengthAccess(condition.rightExpression))) {
this.relevantNodes.push(node) this.relevantNodes.push(node)
} }
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
report (compilationResults: CompilationResult): ReportObj[] { report (compilationResults: CompilationResult): ReportObj[] {
const version = getCompilerVersion(compilationResults.contracts) const version = getCompilerVersion(compilationResults.contracts)
return this.relevantNodes.map((node) => { return this.relevantNodes.map((node) => {
return { return {
warning: `Loops that do not have a fixed number of iterations, for example, loops that depend on storage values, have to be used carefully. Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. \n Additionally, using unbounded loops incurs in a lot of avoidable gas costs. Carefully test how many items at maximum you can pass to such functions to make it successful.`, warning: 'Loops that do not have a fixed number of iterations, for example, loops that depend on storage values, have to be used carefully. Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. \n Additionally, using unbounded loops incurs in a lot of avoidable gas costs. Carefully test how many items at maximum you can pass to such functions to make it successful.',
location: node.src, location: node.src,
more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops` more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops`
} }
......
'use strict' 'use strict'
import { FunctionHLAst, ContractHLAst, FunctionCallGraph, ContractCallGraph, Context, FunctionCallAstNode } from "../../types" import { FunctionHLAst, ContractHLAst, FunctionCallGraph, ContractCallGraph, Context, FunctionCallAstNode } from '../../types'
import { isLocalCallGraphRelevantNode, isExternalDirectCall, getFullQualifiedFunctionCallIdent, import {
getFullQuallyfiedFuncDefinitionIdent, getContractName } from './staticAnalysisCommon' isLocalCallGraphRelevantNode, isExternalDirectCall, getFullQualifiedFunctionCallIdent,
getFullQuallyfiedFuncDefinitionIdent, getContractName
} from './staticAnalysisCommon'
type filterNodesFunction = (node: FunctionCallAstNode) => boolean type filterNodesFunction = (node: FunctionCallAstNode) => boolean
type NodeIdentFunction = (node: FunctionCallAstNode) => string type NodeIdentFunction = (node: FunctionCallAstNode) => string
type FunDefIdentFunction = (node: FunctionHLAst) => string type FunDefIdentFunction = (node: FunctionHLAst) => string
function buildLocalFuncCallGraphInternal (functions: FunctionHLAst[], nodeFilter: filterNodesFunction , extractNodeIdent: NodeIdentFunction, extractFuncDefIdent: FunDefIdentFunction): Record<string, FunctionCallGraph> { function buildLocalFuncCallGraphInternal (functions: FunctionHLAst[], nodeFilter: filterNodesFunction, extractNodeIdent: NodeIdentFunction, extractFuncDefIdent: FunDefIdentFunction): Record<string, FunctionCallGraph> {
const callGraph: Record<string, FunctionCallGraph> = {} const callGraph: Record<string, FunctionCallGraph> = {}
functions.forEach((func: FunctionHLAst) => { functions.forEach((func: FunctionHLAst) => {
const calls: string[] = func.relevantNodes const calls: string[] = func.relevantNodes
...@@ -76,7 +78,7 @@ function analyseCallGraphInternal (callGraph: Record<string, ContractCallGraph>, ...@@ -76,7 +78,7 @@ function analyseCallGraphInternal (callGraph: Record<string, ContractCallGraph>,
visited[funcName] = true visited[funcName] = true
return combinator(current.node.relevantNodes.reduce((acc, val) => combinator(acc, nodeCheck(val, context)), false), return combinator(current.node.relevantNodes.reduce((acc, val) => combinator(acc, nodeCheck(val, context)), false),
current.calls.reduce((acc, val) => combinator(acc, analyseCallGraphInternal(callGraph, val, context, combinator, nodeCheck, visited)), false)) current.calls.reduce((acc, val) => combinator(acc, analyseCallGraphInternal(callGraph, val, context, combinator, nodeCheck, visited)), false))
} }
export function resolveCallGraphSymbol (callGraph: Record<string, ContractCallGraph>, funcName: string): FunctionCallGraph | undefined { export function resolveCallGraphSymbol (callGraph: Record<string, ContractCallGraph>, funcName: string): FunctionCallGraph | undefined {
...@@ -92,7 +94,7 @@ function resolveCallGraphSymbolInternal (callGraph: Record<string, ContractCallG ...@@ -92,7 +94,7 @@ function resolveCallGraphSymbolInternal (callGraph: Record<string, ContractCallG
const currentContract: ContractCallGraph = callGraph[contractPart] const currentContract: ContractCallGraph = callGraph[contractPart]
if (!(currentContract === undefined)) { if (!(currentContract === undefined)) {
current = currentContract.functions[funcName] current = currentContract.functions[funcName]
// resolve inheritance hierarchy // resolve inheritance hierarchy
if (current === undefined) { if (current === undefined) {
// resolve inheritance lookup in linearized fashion // resolve inheritance lookup in linearized fashion
const inheritsFromNames: string[] = currentContract.contract.inheritsFrom.reverse() const inheritsFromNames: string[] = currentContract.contract.inheritsFrom.reverse()
...@@ -108,6 +110,5 @@ function resolveCallGraphSymbolInternal (callGraph: Record<string, ContractCallG ...@@ -108,6 +110,5 @@ function resolveCallGraphSymbolInternal (callGraph: Record<string, ContractCallG
throw new Error('functionCallGraph.js: function does not have full qualified name.') throw new Error('functionCallGraph.js: function does not have full qualified name.')
} }
if (current === undefined && !silent) console.log(`static analysis functionCallGraph.js: ${funcName} not found in function call graph.`) if (current === undefined && !silent) console.log(`static analysis functionCallGraph.js: ${funcName} not found in function call graph.`)
if(current !== null) if (current !== null) { return current }
return current
} }
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { getFunctionDefinitionName, helpers, isVariableTurnedIntoGetter, getMethodParamsSplittedTypeDesc } from './staticAnalysisCommon' import { getFunctionDefinitionName, helpers, isVariableTurnedIntoGetter, getMethodParamsSplittedTypeDesc } from './staticAnalysisCommon'
import { ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, CompiledContract, AnalyzerModule, import {
FunctionDefinitionAstNode, VariableDeclarationAstNode, SupportedVersion } from './../../types' ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, CompiledContract, AnalyzerModule,
FunctionDefinitionAstNode, VariableDeclarationAstNode, SupportedVersion
} from './../../types'
export default class gasCosts implements AnalyzerModule { export default class gasCosts implements AnalyzerModule {
name = `Gas costs: ` name = 'Gas costs: '
description = `Too high gas requirement of functions` description = 'Too high gas requirement of functions'
category: ModuleCategory = category.GAS category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -15,22 +17,19 @@ export default class gasCosts implements AnalyzerModule { ...@@ -15,22 +17,19 @@ export default class gasCosts implements AnalyzerModule {
warningNodes: any[] = [] warningNodes: any[] = []
visit (node: FunctionDefinitionAstNode | VariableDeclarationAstNode): void { visit (node: FunctionDefinitionAstNode | VariableDeclarationAstNode): void {
if ((node.nodeType === 'FunctionDefinition' && node.kind !== 'constructor' && node.implemented) || if ((node.nodeType === 'FunctionDefinition' && node.kind !== 'constructor' && node.implemented) ||
(node.nodeType === 'VariableDeclaration' && isVariableTurnedIntoGetter(node))) (node.nodeType === 'VariableDeclaration' && isVariableTurnedIntoGetter(node))) { this.warningNodes.push(node) }
this.warningNodes.push(node)
} }
report (compilationResults: CompilationResult): ReportObj[] { report (compilationResults: CompilationResult): ReportObj[] {
const report: ReportObj[] = [] const report: ReportObj[] = []
const methodsWithSignature: Record<string, string>[] = this.warningNodes.map(node => { const methodsWithSignature: Record<string, string>[] = this.warningNodes.map(node => {
let signature: string; let signature: string
if(node.nodeType === 'FunctionDefinition'){ if (node.nodeType === 'FunctionDefinition') {
const functionName: string = getFunctionDefinitionName(node) const functionName: string = getFunctionDefinitionName(node)
signature = helpers.buildAbiSignature(functionName, getMethodParamsSplittedTypeDesc(node, compilationResults.contracts)) signature = helpers.buildAbiSignature(functionName, getMethodParamsSplittedTypeDesc(node, compilationResults.contracts))
} } else { signature = node.name + '()' }
else
signature = node.name + '()'
return { return {
name: node.name, name: node.name,
src: node.src, src: node.src,
...@@ -42,8 +41,8 @@ export default class gasCosts implements AnalyzerModule { ...@@ -42,8 +41,8 @@ export default class gasCosts implements AnalyzerModule {
for (const contractName in compilationResults.contracts[filename]) { for (const contractName in compilationResults.contracts[filename]) {
const contract: CompiledContract = compilationResults.contracts[filename][contractName] const contract: CompiledContract = compilationResults.contracts[filename][contractName]
const methodGas: Record<string, any> | undefined = this.checkMethodGas(contract, method.signature) const methodGas: Record<string, any> | undefined = this.checkMethodGas(contract, method.signature)
if(methodGas && methodGas.isInfinite) { if (methodGas && methodGas.isInfinite) {
if(methodGas.isFallback) { if (methodGas.isFallback) {
report.push({ report.push({
warning: `Fallback function of contract ${contractName} requires too much gas (${methodGas.msg}). warning: `Fallback function of contract ${contractName} requires too much gas (${methodGas.msg}).
If the fallback function requires more than 2300 gas, the contract cannot receive Ether.`, If the fallback function requires more than 2300 gas, the contract cannot receive Ether.`,
...@@ -57,7 +56,7 @@ export default class gasCosts implements AnalyzerModule { ...@@ -57,7 +56,7 @@ export default class gasCosts implements AnalyzerModule {
(this includes clearing or copying arrays in storage)`, (this includes clearing or copying arrays in storage)`,
location: method.src location: method.src
}) })
} }
} else continue } else continue
} }
} }
...@@ -65,17 +64,17 @@ export default class gasCosts implements AnalyzerModule { ...@@ -65,17 +64,17 @@ export default class gasCosts implements AnalyzerModule {
return report return report
} }
private checkMethodGas(contract: CompiledContract, methodSignature: string): Record<string, any> | undefined { private checkMethodGas (contract: CompiledContract, methodSignature: string): Record<string, any> | undefined {
if(contract.evm && contract.evm.gasEstimates && contract.evm.gasEstimates.external) { if (contract.evm && contract.evm.gasEstimates && contract.evm.gasEstimates.external) {
if(methodSignature === '()') { if (methodSignature === '()') {
const fallback: string = contract.evm.gasEstimates.external[''] const fallback: string = contract.evm.gasEstimates.external['']
if (fallback !== undefined && (fallback === null || parseInt(fallback) >= 2100 || fallback === 'infinite')) { if (fallback !== undefined && (fallback === null || parseInt(fallback) >= 2100 || fallback === 'infinite')) {
return { return {
isInfinite: true, isInfinite: true,
isFallback: true, isFallback: true,
msg: fallback msg: fallback
} }
} }
} else { } else {
const gas: string = contract.evm.gasEstimates.external[methodSignature] const gas: string = contract.evm.gasEstimates.external[methodSignature]
const gasString: string = gas === null ? 'unknown or not constant' : 'is ' + gas const gasString: string = gas === null ? 'unknown or not constant' : 'is ' + gas
...@@ -85,8 +84,8 @@ export default class gasCosts implements AnalyzerModule { ...@@ -85,8 +84,8 @@ export default class gasCosts implements AnalyzerModule {
isFallback: false, isFallback: false,
msg: gasString msg: gasString
} }
} }
} }
} }
} }
} }
import { default as category } from './categories' import category from './categories'
import { isRequireCall, isAssertCall, getCompilerVersion } from './staticAnalysisCommon' import { isRequireCall, isAssertCall, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion } from './../../types'
export default class guardConditions implements AnalyzerModule { export default class guardConditions implements AnalyzerModule {
guards: FunctionCallAstNode[] = [] guards: FunctionCallAstNode[] = []
name = `Guard conditions: ` name = 'Guard conditions: '
description = `Ensure appropriate use of require/assert` description = 'Ensure appropriate use of require/assert'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -22,7 +22,7 @@ export default class guardConditions implements AnalyzerModule { ...@@ -22,7 +22,7 @@ export default class guardConditions implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts) const version = getCompilerVersion(compilationResults.contracts)
return this.guards.map((node) => { return this.guards.map((node) => {
return { return {
warning: `Use "assert(x)" if you never ever want x to be false, not in any circumstance (apart from a bug in your code). Use "require(x)" if x can be false, due to e.g. invalid input or a failing external component.`, warning: 'Use "assert(x)" if you never ever want x to be false, not in any circumstance (apart from a bug in your code). Use "require(x)" if x can be false, due to e.g. invalid input or a failing external component.',
location: node.src, location: node.src,
more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#error-handling-assert-require-revert-and-exceptions` more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#error-handling-assert-require-revert-and-exceptions`
} }
......
...@@ -18,4 +18,4 @@ export { default as stringBytesLength } from './stringBytesLength' ...@@ -18,4 +18,4 @@ export { default as stringBytesLength } from './stringBytesLength'
export { default as intDivisionTruncate } from './intDivisionTruncate' export { default as intDivisionTruncate } from './intDivisionTruncate'
export { default as etherTransferInLoop } from './etherTransferInLoop' export { default as etherTransferInLoop } from './etherTransferInLoop'
export { default as deleteFromDynamicArray } from './deleteFromDynamicArray' export { default as deleteFromDynamicArray } from './deleteFromDynamicArray'
export { default as forLoopIteratesOverDynamicArray } from './forLoopIteratesOverDynamicArray' export { default as forLoopIteratesOverDynamicArray } from './forLoopIteratesOverDynamicArray'
\ No newline at end of file
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, InlineAssemblyAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, InlineAssemblyAstNode, SupportedVersion } from './../../types'
import { getCompilerVersion } from './staticAnalysisCommon' import { getCompilerVersion } from './staticAnalysisCommon'
export default class inlineAssembly implements AnalyzerModule { export default class inlineAssembly implements AnalyzerModule {
inlineAssNodes: InlineAssemblyAstNode[] = [] inlineAssNodes: InlineAssemblyAstNode[] = []
name = `Inline assembly: ` name = 'Inline assembly: '
description = `Inline assembly used` description = 'Inline assembly used'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -14,7 +14,7 @@ export default class inlineAssembly implements AnalyzerModule { ...@@ -14,7 +14,7 @@ export default class inlineAssembly implements AnalyzerModule {
} }
visit (node: InlineAssemblyAstNode): void { visit (node: InlineAssemblyAstNode): void {
if(node.nodeType === 'InlineAssembly') this.inlineAssNodes.push(node) if (node.nodeType === 'InlineAssembly') this.inlineAssNodes.push(node)
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
......
import { default as category } from './categories' import category from './categories'
import { isIntDivision } from './staticAnalysisCommon' import { isIntDivision } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, BinaryOperationAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, BinaryOperationAstNode, SupportedVersion } from './../../types'
export default class intDivisionTruncate implements AnalyzerModule { export default class intDivisionTruncate implements AnalyzerModule {
warningNodes: BinaryOperationAstNode[] = [] warningNodes: BinaryOperationAstNode[] = []
name = `Data truncated: ` name = 'Data truncated: '
description = `Division on int/uint values truncates the result` description = 'Division on int/uint values truncates the result'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
......
import { default as category } from './categories' import category from './categories'
import { isLLCall, isLLDelegatecall, isLLCallcode, isLLCall04, isLLDelegatecall04, isLLSend04, isLLSend, lowLevelCallTypes, getCompilerVersion } from './staticAnalysisCommon' import { isLLCall, isLLDelegatecall, isLLCallcode, isLLCall04, isLLDelegatecall04, isLLSend04, isLLSend, lowLevelCallTypes, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types'
interface llcNode { interface llcNode {
node: MemberAccessAstNode node: MemberAccessAstNode
...@@ -10,8 +10,8 @@ interface llcNode { ...@@ -10,8 +10,8 @@ interface llcNode {
export default class lowLevelCalls implements AnalyzerModule { export default class lowLevelCalls implements AnalyzerModule {
llcNodes: llcNode[] = [] llcNodes: llcNode[] = []
name = `Low level calls: ` name = 'Low level calls: '
description = `Should only be used by experienced devs` description = 'Should only be used by experienced devs'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -20,19 +20,19 @@ export default class lowLevelCalls implements AnalyzerModule { ...@@ -20,19 +20,19 @@ export default class lowLevelCalls implements AnalyzerModule {
visit (node : MemberAccessAstNode): void { visit (node : MemberAccessAstNode): void {
if (isLLCall(node)) { if (isLLCall(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.CALL}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALL })
} else if (isLLDelegatecall(node)) { } else if (isLLDelegatecall(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.DELEGATECALL}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.DELEGATECALL })
} else if (isLLSend(node)) { } else if (isLLSend(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.SEND}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.SEND })
} else if (isLLDelegatecall04(node)) { } else if (isLLDelegatecall04(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.DELEGATECALL}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.DELEGATECALL })
} else if (isLLSend04(node)) { } else if (isLLSend04(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.SEND}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.SEND })
} else if (isLLCall04(node)) { } else if (isLLCall04(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.CALL}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALL })
} else if (isLLCallcode(node)) { } else if (isLLCallcode(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.CALLCODE}) this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALLCODE })
} }
} }
...@@ -73,4 +73,3 @@ export default class lowLevelCalls implements AnalyzerModule { ...@@ -73,4 +73,3 @@ export default class lowLevelCalls implements AnalyzerModule {
}) })
} }
} }
import { default as category } from './categories' import category from './categories'
import { hasFunctionBody, getFullQuallyfiedFuncDefinitionIdent, getEffectedVariableName } from './staticAnalysisCommon' import { hasFunctionBody, getFullQuallyfiedFuncDefinitionIdent, getEffectedVariableName } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView' import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, import {
VisitFunction, ReportFunction, ReturnAstNode, AssignmentAstNode, SupportedVersion} from './../../types' AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst,
VisitFunction, ReportFunction, ReturnAstNode, AssignmentAstNode, SupportedVersion
} from './../../types'
export default class noReturn implements AnalyzerModule { export default class noReturn implements AnalyzerModule {
name = `No return: ` name = 'No return: '
description = `Function with 'returns' not returning` description = 'Function with \'returns\' not returning'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -17,7 +19,7 @@ export default class noReturn implements AnalyzerModule { ...@@ -17,7 +19,7 @@ export default class noReturn implements AnalyzerModule {
abstractAst: AbstractAst = new AbstractAst() abstractAst: AbstractAst = new AbstractAst()
visit: VisitFunction = this.abstractAst.build_visit( visit: VisitFunction = this.abstractAst.build_visit(
(node: ReturnAstNode | AssignmentAstNode) => node.nodeType === "Return" || node.nodeType === "Assignment" (node: ReturnAstNode | AssignmentAstNode) => node.nodeType === 'Return' || node.nodeType === 'Assignment'
) )
report: ReportFunction = this.abstractAst.build_report(this._report.bind(this)) report: ReportFunction = this.abstractAst.build_report(this._report.bind(this))
...@@ -30,12 +32,12 @@ export default class noReturn implements AnalyzerModule { ...@@ -30,12 +32,12 @@ export default class noReturn implements AnalyzerModule {
if (this.hasNamedAndUnnamedReturns(func)) { if (this.hasNamedAndUnnamedReturns(func)) {
warnings.push({ warnings.push({
warning: `${funcName}: Mixing of named and unnamed return parameters is not advised.`, warning: `${funcName}: Mixing of named and unnamed return parameters is not advised.`,
location: func.node['src'] location: func.node.src
}) })
} else if (this.shouldReturn(func) && !(this.hasReturnStatement(func) || (this.hasNamedReturns(func) && this.hasAssignToAllNamedReturns(func)))) { } else if (this.shouldReturn(func) && !(this.hasReturnStatement(func) || (this.hasNamedReturns(func) && this.hasAssignToAllNamedReturns(func)))) {
warnings.push({ warnings.push({
warning: `${funcName}: Defines a return type but never explicitly returns a value.`, warning: `${funcName}: Defines a return type but never explicitly returns a value.`,
location: func.node['src'] location: func.node.src
}) })
} }
}) })
...@@ -48,12 +50,12 @@ export default class noReturn implements AnalyzerModule { ...@@ -48,12 +50,12 @@ export default class noReturn implements AnalyzerModule {
} }
private hasReturnStatement (func: FunctionHLAst): boolean { private hasReturnStatement (func: FunctionHLAst): boolean {
return func.relevantNodes.filter(n => n.nodeType === "Return").length > 0 return func.relevantNodes.filter(n => n.nodeType === 'Return').length > 0
} }
private hasAssignToAllNamedReturns (func: FunctionHLAst): boolean { private hasAssignToAllNamedReturns (func: FunctionHLAst): boolean {
const namedReturns: string[] = func.returns.filter(n => n.name.length > 0).map((n) => n.name) const namedReturns: string[] = func.returns.filter(n => n.name.length > 0).map((n) => n.name)
const assignedVars: string[] = func.relevantNodes.filter(n => n.nodeType === "Assignment").map(getEffectedVariableName) const assignedVars: string[] = func.relevantNodes.filter(n => n.nodeType === 'Assignment').map(getEffectedVariableName)
const diff: string[] = namedReturns.filter(e => !assignedVars.includes(e)) const diff: string[] = namedReturns.filter(e => !assignedVars.includes(e))
return diff.length === 0 return diff.length === 0
} }
......
import { default as category } from './categories' import category from './categories'
import { isStatement, isSelfdestructCall } from './staticAnalysisCommon' import { isStatement, isSelfdestructCall } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView' import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VisitFunction, ReportFunction, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VisitFunction, ReportFunction, SupportedVersion } from './../../types'
export default class selfdestruct implements AnalyzerModule { export default class selfdestruct implements AnalyzerModule {
name = `Selfdestruct: ` name = 'Selfdestruct: '
description = `Contracts using destructed contract can be broken` description = 'Contracts using destructed contract can be broken'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.HEURISTIC algorithm: ModuleAlgorithm = algorithm.HEURISTIC
version: SupportedVersion = { version: SupportedVersion = {
...@@ -16,7 +16,7 @@ export default class selfdestruct implements AnalyzerModule { ...@@ -16,7 +16,7 @@ export default class selfdestruct implements AnalyzerModule {
abstractAst: AbstractAst = new AbstractAst() abstractAst: AbstractAst = new AbstractAst()
visit: VisitFunction = this.abstractAst.build_visit( visit: VisitFunction = this.abstractAst.build_visit(
(node: any) => isStatement(node) || (node.nodeType=== 'FunctionCall' && isSelfdestructCall(node)) (node: any) => isStatement(node) || (node.nodeType === 'FunctionCall' && isSelfdestructCall(node))
) )
report: ReportFunction = this.abstractAst.build_report(this._report.bind(this)) report: ReportFunction = this.abstractAst.build_report(this._report.bind(this))
...@@ -30,7 +30,7 @@ export default class selfdestruct implements AnalyzerModule { ...@@ -30,7 +30,7 @@ export default class selfdestruct implements AnalyzerModule {
func.relevantNodes.forEach((node) => { func.relevantNodes.forEach((node) => {
if (isSelfdestructCall(node)) { if (isSelfdestructCall(node)) {
warnings.push({ warnings.push({
warning: `Use of selfdestruct: Can block calling contracts unexpectedly. Be especially careful if this contract is planned to be used by other contracts (i.e. library contracts, interactions). Selfdestruction of the callee contract can leave callers in an inoperable state.`, warning: 'Use of selfdestruct: Can block calling contracts unexpectedly. Be especially careful if this contract is planned to be used by other contracts (i.e. library contracts, interactions). Selfdestruction of the callee contract can leave callers in an inoperable state.',
location: node.src, location: node.src,
more: 'https://paritytech.io/blog/security-alert.html' more: 'https://paritytech.io/blog/security-alert.html'
}) })
...@@ -38,7 +38,7 @@ export default class selfdestruct implements AnalyzerModule { ...@@ -38,7 +38,7 @@ export default class selfdestruct implements AnalyzerModule {
} }
if (isStatement(node) && hasSelf) { if (isStatement(node) && hasSelf) {
warnings.push({ warnings.push({
warning: `Use of selfdestruct: No code after selfdestruct is executed. Selfdestruct is a terminal.`, warning: 'Use of selfdestruct: No code after selfdestruct is executed. Selfdestruct is a terminal.',
location: node.src, location: node.src,
more: `https://solidity.readthedocs.io/en/${version}/introduction-to-smart-contracts.html#deactivate-and-self-destruct` more: `https://solidity.readthedocs.io/en/${version}/introduction-to-smart-contracts.html#deactivate-and-self-destruct`
}) })
......
import { default as category } from './categories' import category from './categories'
import { getDeclaredVariableName, getFullQuallyfiedFuncDefinitionIdent } from './staticAnalysisCommon' import { getDeclaredVariableName, getFullQuallyfiedFuncDefinitionIdent } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView' import AbstractAst from './abstractAstView'
import { get } from 'fast-levenshtein' import { get } from 'fast-levenshtein'
import { util } from '@remix-project/remix-lib' import { util } from '@remix-project/remix-lib'
import { AstWalker } from '@remix-project/remix-astwalker' import { AstWalker } from '@remix-project/remix-astwalker'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, VariableDeclarationAstNode, VisitFunction, ReportFunction, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, VariableDeclarationAstNode, VisitFunction, ReportFunction, SupportedVersion } from './../../types'
interface SimilarRecord { interface SimilarRecord {
var1: string var1: string
...@@ -14,8 +14,8 @@ interface SimilarRecord { ...@@ -14,8 +14,8 @@ interface SimilarRecord {
} }
export default class similarVariableNames implements AnalyzerModule { export default class similarVariableNames implements AnalyzerModule {
name = `Similar variable names: ` name = 'Similar variable names: '
description = `Variable names are too similar` description = 'Variable names are too similar'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -47,17 +47,17 @@ export default class similarVariableNames implements AnalyzerModule { ...@@ -47,17 +47,17 @@ export default class similarVariableNames implements AnalyzerModule {
const vars: string[] = this.getFunctionVariables(contract, func).map(getDeclaredVariableName) const vars: string[] = this.getFunctionVariables(contract, func).map(getDeclaredVariableName)
this.findSimilarVarNames(vars).map((sim) => { this.findSimilarVarNames(vars).map((sim) => {
// check if function is implemented // check if function is implemented
if(func.node.implemented) { if (func.node.implemented) {
const astWalker = new AstWalker() const astWalker = new AstWalker()
const functionBody: any = func.node.body const functionBody: any = func.node.body
// Walk through all statements of function // Walk through all statements of function
astWalker.walk(functionBody, (node) => { astWalker.walk(functionBody, (node) => {
// check if these is an identifier node which is one of the tracked similar variables // check if these is an identifier node which is one of the tracked similar variables
if ((node.nodeType === 'Identifier' || node.nodeType === 'VariableDeclaration') if ((node.nodeType === 'Identifier' || node.nodeType === 'VariableDeclaration') &&
&& (node.name === sim.var1 || node.name === sim.var2)) { (node.name === sim.var1 || node.name === sim.var2)) {
warnings.push({ warnings.push({
warning: `${funcName} : Variables have very similar names "${sim.var1}" and "${sim.var2}". ${hasModifiersComments} ${multipleContractsWithSameNameComments}`, warning: `${funcName} : Variables have very similar names "${sim.var1}" and "${sim.var2}". ${hasModifiersComments} ${multipleContractsWithSameNameComments}`,
location: node['src'] location: node.src
}) })
} }
return true return true
...@@ -73,9 +73,9 @@ export default class similarVariableNames implements AnalyzerModule { ...@@ -73,9 +73,9 @@ export default class similarVariableNames implements AnalyzerModule {
const similar: SimilarRecord[] = [] const similar: SimilarRecord[] = []
const comb: Record<string, boolean> = {} const comb: Record<string, boolean> = {}
vars.map((varName1: string) => vars.map((varName2: string) => { vars.map((varName1: string) => vars.map((varName2: string) => {
if (varName1.length > 1 && varName2.length > 1 && if (varName1.length > 1 && varName2.length > 1 &&
varName2 !== varName1 && !this.isCommonPrefixedVersion(varName1, varName2) && varName2 !== varName1 && !this.isCommonPrefixedVersion(varName1, varName2) &&
!this.isCommonNrSuffixVersion(varName1, varName2) && !this.isCommonNrSuffixVersion(varName1, varName2) &&
!(comb[varName1 + ';' + varName2] || comb[varName2 + ';' + varName1])) { !(comb[varName1 + ';' + varName2] || comb[varName2 + ';' + varName1])) {
comb[varName1 + ';' + varName2] = true comb[varName1 + ';' + varName2] = true
const distance: number = get(varName1, varName2) const distance: number = get(varName1, varName2)
......
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { isStringToBytesConversion, isBytesLengthCheck, getCompilerVersion } from './staticAnalysisCommon' import { isStringToBytesConversion, isBytesLengthCheck, getCompilerVersion } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, FunctionCallAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, FunctionCallAstNode, SupportedVersion } from './../../types'
export default class stringBytesLength implements AnalyzerModule { export default class stringBytesLength implements AnalyzerModule {
name = `String length: ` name = 'String length: '
description = `Bytes length != String length` description = 'Bytes length != String length'
category: ModuleCategory = category.MISC category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -16,8 +16,8 @@ export default class stringBytesLength implements AnalyzerModule { ...@@ -16,8 +16,8 @@ export default class stringBytesLength implements AnalyzerModule {
bytesLengthChecks: MemberAccessAstNode[] = [] bytesLengthChecks: MemberAccessAstNode[] = []
visit (node: FunctionCallAstNode | MemberAccessAstNode): void { visit (node: FunctionCallAstNode | MemberAccessAstNode): void {
if (node.nodeType === "FunctionCall" && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node) if (node.nodeType === 'FunctionCall' && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node)
else if (node.nodeType === "MemberAccess" && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node) else if (node.nodeType === 'MemberAccess' && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node)
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
...@@ -25,7 +25,7 @@ export default class stringBytesLength implements AnalyzerModule { ...@@ -25,7 +25,7 @@ export default class stringBytesLength implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts) const version = getCompilerVersion(compilationResults.contracts)
if (this.stringToBytesConversions.length > 0 && this.bytesLengthChecks.length > 0) { if (this.stringToBytesConversions.length > 0 && this.bytesLengthChecks.length > 0) {
return [{ return [{
warning: `"bytes" and "string" lengths are not the same since strings are assumed to be UTF-8 encoded (according to the ABI defintion) therefore one character is not nessesarily encoded in one byte of data.`, warning: '"bytes" and "string" lengths are not the same since strings are assumed to be UTF-8 encoded (according to the ABI defintion) therefore one character is not nessesarily encoded in one byte of data.',
location: this.bytesLengthChecks[0].src, location: this.bytesLengthChecks[0].src,
more: `https://solidity.readthedocs.io/en/${version}/abi-spec.html#argument-encoding` more: `https://solidity.readthedocs.io/en/${version}/abi-spec.html#argument-encoding`
}] }]
......
import { default as category } from './categories' import category from './categories'
import { isThisLocalCall, getCompilerVersion } from './staticAnalysisCommon' import { isThisLocalCall, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types'
export default class thisLocal implements AnalyzerModule { export default class thisLocal implements AnalyzerModule {
warningNodes: MemberAccessAstNode[] = [] warningNodes: MemberAccessAstNode[] = []
name = `This on local calls: ` name = 'This on local calls: '
description = `Invocation of local functions via 'this'` description = 'Invocation of local functions via \'this\''
category: ModuleCategory = category.GAS category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -22,7 +22,7 @@ export default class thisLocal implements AnalyzerModule { ...@@ -22,7 +22,7 @@ export default class thisLocal implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts) const version = getCompilerVersion(compilationResults.contracts)
return this.warningNodes.map(function (item, i) { return this.warningNodes.map(function (item, i) {
return { return {
warning: `Use of "this" for local functions: Never use "this" to call functions in the same contract, it only consumes more gas than normal local calls.`, warning: 'Use of "this" for local functions: Never use "this" to call functions in the same contract, it only consumes more gas than normal local calls.',
location: item.src, location: item.src,
more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#external-function-calls` more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#external-function-calls`
} }
......
import { default as category } from './categories' import category from './categories'
import { default as algorithm } from './algorithmCategories' import algorithm from './algorithmCategories'
import { isTxOriginAccess, getCompilerVersion } from './staticAnalysisCommon' import { isTxOriginAccess, getCompilerVersion } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types' import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types'
export default class txOrigin implements AnalyzerModule { export default class txOrigin implements AnalyzerModule {
txOriginNodes: MemberAccessAstNode[] = [] txOriginNodes: MemberAccessAstNode[] = []
name = `Transaction origin: ` name = 'Transaction origin: '
description = `'tx.origin' used` description = '\'tx.origin\' used'
category: ModuleCategory = category.SECURITY category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = { version: SupportedVersion = {
...@@ -15,7 +15,6 @@ export default class txOrigin implements AnalyzerModule { ...@@ -15,7 +15,6 @@ export default class txOrigin implements AnalyzerModule {
visit (node: MemberAccessAstNode): void { visit (node: MemberAccessAstNode): void {
if (isTxOriginAccess(node)) this.txOriginNodes.push(node) if (isTxOriginAccess(node)) this.txOriginNodes.push(node)
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
......
...@@ -39,9 +39,9 @@ export interface ReportObj { ...@@ -39,9 +39,9 @@ export interface ReportObj {
// s:l:f // s:l:f
// Where, // Where,
// s is the byte-offset to the start of the range in the source file, // s is the byte-offset to the start of the range in the source file,
// l is the length of the source range in bytes and // l is the length of the source range in bytes and
// f is the source index mentioned above. // f is the source index mentioned above.
export interface AnalysisReportObj { export interface AnalysisReportObj {
...@@ -57,7 +57,7 @@ export type AnalysisReport = { ...@@ -57,7 +57,7 @@ export type AnalysisReport = {
} }
export interface CompilationResult { export interface CompilationResult {
error?: CompilationError, error?: CompilationError,
/** not present if no errors/warnings were encountered */ /** not present if no errors/warnings were encountered */
errors?: CompilationError[] errors?: CompilationError[]
/** This contains the file-level outputs. In can be limited/filtered by the outputSelection settings */ /** This contains the file-level outputs. In can be limited/filtered by the outputSelection settings */
...@@ -121,9 +121,9 @@ export interface ContractCallGraph { ...@@ -121,9 +121,9 @@ export interface ContractCallGraph {
functions: Record<string, FunctionCallGraph> functions: Record<string, FunctionCallGraph>
} }
///////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////
///////////// Specfic AST Nodes ///////////////////////////// /// ////////// Specfic AST Nodes /////////////////////////////
///////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////
interface TypeDescription { interface TypeDescription {
typeIdentifier: string typeIdentifier: string
...@@ -629,10 +629,9 @@ export interface CommonAstNode { ...@@ -629,10 +629,9 @@ export interface CommonAstNode {
[x: string]: any [x: string]: any
} }
/// //////////////////////////////////////////////////////
///////////////////////////////////////////////////////// /// ////////// YUL AST Nodes /////////////////////////////
///////////// YUL AST Nodes ///////////////////////////// /// //////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
export interface YulTypedNameAstNode { export interface YulTypedNameAstNode {
name: string name: string
...@@ -673,13 +672,12 @@ export interface CommonYulAstNode { ...@@ -673,13 +672,12 @@ export interface CommonYulAstNode {
src: string src: string
[x: string]: any [x: string]: any
} }
/// ////////
/////////// // ERROR //
// ERROR // /// ////////
///////////
export interface CompilationError {
export interface CompilationError {
/** Location within the source file */ /** Location within the source file */
sourceLocation?: { sourceLocation?: {
file: string file: string
...@@ -696,7 +694,7 @@ export interface CommonYulAstNode { ...@@ -696,7 +694,7 @@ export interface CommonYulAstNode {
/** the message formatted with source location */ /** the message formatted with source location */
formattedMessage?: string formattedMessage?: string
} }
type CompilationErrorType = type CompilationErrorType =
| 'JSONError' | 'JSONError'
| 'IOError' | 'IOError'
...@@ -711,21 +709,21 @@ export interface CommonYulAstNode { ...@@ -711,21 +709,21 @@ export interface CommonYulAstNode {
| 'CompilerError' | 'CompilerError'
| 'FatalError' | 'FatalError'
| 'Warning' | 'Warning'
//////////// /// /////////
// SOURCE // // SOURCE //
//////////// /// /////////
export interface CompilationSource { export interface CompilationSource {
/** Identifier of the source (used in source maps) */ /** Identifier of the source (used in source maps) */
id: number id: number
/** The AST object */ /** The AST object */
ast: AstNode ast: AstNode
} }
///////// /// //////
// AST // // AST //
///////// /// //////
export interface AstNode { export interface AstNode {
absolutePath?: string absolutePath?: string
exportedSymbols?: Record<string, unknown> exportedSymbols?: Record<string, unknown>
id: number id: number
...@@ -739,8 +737,8 @@ export interface CommonYulAstNode { ...@@ -739,8 +737,8 @@ export interface CommonYulAstNode {
symbolAliases?: Array<string> symbolAliases?: Array<string>
[x: string]: any [x: string]: any
} }
export interface AstNodeAtt { export interface AstNodeAtt {
operator?: string operator?: string
string?: null string?: null
type?: string type?: string
...@@ -753,11 +751,11 @@ export interface CommonYulAstNode { ...@@ -753,11 +751,11 @@ export interface CommonYulAstNode {
absolutePath?: string absolutePath?: string
[x: string]: any [x: string]: any
} }
////////////// /// ///////////
// CONTRACT // // CONTRACT //
////////////// /// ///////////
export interface CompiledContract { export interface CompiledContract {
/** The Ethereum Contract ABI. If empty, it is represented as an empty array. */ /** The Ethereum Contract ABI. If empty, it is represented as an empty array. */
abi: ABIDescription[] abi: ABIDescription[]
// See the Metadata Output documentation (serialised JSON string) // See the Metadata Output documentation (serialised JSON string)
...@@ -802,13 +800,13 @@ export interface CommonYulAstNode { ...@@ -802,13 +800,13 @@ export interface CommonYulAstNode {
wasm: string wasm: string
} }
} }
///////// /// //////
// ABI // // ABI //
///////// /// //////
export type ABIDescription = FunctionDescription | EventDescription export type ABIDescription = FunctionDescription | EventDescription
export interface FunctionDescription { export interface FunctionDescription {
/** Type of the method. default is 'function' */ /** Type of the method. default is 'function' */
type?: 'function' | 'constructor' | 'fallback' | 'receive' type?: 'function' | 'constructor' | 'fallback' | 'receive'
/** The name of the function. Constructor and fallback function never have name */ /** The name of the function. Constructor and fallback function never have name */
...@@ -824,8 +822,8 @@ export interface CommonYulAstNode { ...@@ -824,8 +822,8 @@ export interface CommonYulAstNode {
/** true if function is either pure or view, false otherwise. Default is false */ /** true if function is either pure or view, false otherwise. Default is false */
constant?: boolean constant?: boolean
} }
export interface EventDescription { export interface EventDescription {
type: 'event' type: 'event'
name: string name: string
inputs: ABIParameter & inputs: ABIParameter &
...@@ -836,8 +834,8 @@ export interface CommonYulAstNode { ...@@ -836,8 +834,8 @@ export interface CommonYulAstNode {
/** true if the event was declared as anonymous. */ /** true if the event was declared as anonymous. */
anonymous: boolean anonymous: boolean
} }
export interface ABIParameter { export interface ABIParameter {
internalType: string internalType: string
/** The name of the parameter */ /** The name of the parameter */
name: string name: string
...@@ -846,8 +844,8 @@ export interface CommonYulAstNode { ...@@ -846,8 +844,8 @@ export interface CommonYulAstNode {
/** Used for tuple types */ /** Used for tuple types */
components?: ABIParameter[] components?: ABIParameter[]
} }
export type ABITypeParameter = export type ABITypeParameter =
| 'uint' | 'uint'
| 'uint[]' // TODO : add <M> | 'uint[]' // TODO : add <M>
| 'int' | 'int'
...@@ -868,38 +866,38 @@ export interface CommonYulAstNode { ...@@ -868,38 +866,38 @@ export interface CommonYulAstNode {
| 'tuple[]' | 'tuple[]'
| string // Fallback | string // Fallback
/////////////////////////// /// ////////////////////////
// NATURAL SPECIFICATION // // NATURAL SPECIFICATION //
/////////////////////////// /// ////////////////////////
// Userdoc // Userdoc
export interface UserDocumentation { export interface UserDocumentation {
methods: UserMethodList methods: UserMethodList
notice: string notice: string
} }
export type UserMethodList = { export type UserMethodList = {
[functionIdentifier: string]: UserMethodDoc [functionIdentifier: string]: UserMethodDoc
} & { } & {
'constructor'?: string 'constructor'?: string
} }
export interface UserMethodDoc { export interface UserMethodDoc {
notice: string notice: string
} }
// Devdoc // Devdoc
export interface DeveloperDocumentation { export interface DeveloperDocumentation {
author: string author: string
title: string title: string
details: string details: string
methods: DevMethodList methods: DevMethodList
} }
export interface DevMethodList { export interface DevMethodList {
[functionIdentifier: string]: DevMethodDoc [functionIdentifier: string]: DevMethodDoc
} }
export interface DevMethodDoc { export interface DevMethodDoc {
author: string author: string
details: string details: string
return: string return: string
...@@ -907,11 +905,11 @@ export interface CommonYulAstNode { ...@@ -907,11 +905,11 @@ export interface CommonYulAstNode {
[param: string]: string [param: string]: string
} }
} }
////////////// /// ///////////
// BYTECODE // // BYTECODE //
////////////// /// ///////////
export interface BytecodeObject { export interface BytecodeObject {
/** The bytecode as a hex string. */ /** The bytecode as a hex string. */
object: string object: string
/** Opcodes list */ /** Opcodes list */
...@@ -925,4 +923,4 @@ export interface CommonYulAstNode { ...@@ -925,4 +923,4 @@ export interface CommonYulAstNode {
[library: string]: { start: number; length: number }[] [library: string]: { start: number; length: number }[]
} }
} }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment