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

libs linting fix

parent 2e6d289a
......@@ -2,7 +2,9 @@
"extends": "../../.eslintrc",
"rules": {
"@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": ["!**/*"]
}
export { default as CodeAnalysis} from './solidity-analyzer'
export { default as CodeAnalysis } from './solidity-analyzer'
......@@ -9,7 +9,6 @@ type ModuleObj = {
}
export default class staticAnalysisRunner {
/**
* Run analysis (Used by IDE)
* @param compilationResult contract compilation result
......@@ -18,9 +17,9 @@ export default class staticAnalysisRunner {
*/
run (compilationResult: CompilationResult, toRun: number[], callback: ((reports: AnalysisReport[]) => void)): void {
const modules: ModuleObj[] = toRun.map((i) => {
const module = this.modules()[i]
const m = new module()
return { 'name': m.name, 'mod': m }
const Module = this.modules()[i]
const m = new Module()
return { name: m.name, mod: m }
})
this.runWithModuleList(compilationResult, modules, callback)
}
......
import { getStateVariableDeclarationsFromContractNode, getInheritsFromName, getContractName,
import {
getStateVariableDeclarationsFromContractNode, getInheritsFromName, getContractName,
getFunctionOrModifierDefinitionParameterPart, getType, getDeclaredVariableName,
getFunctionDefinitionReturnParameterPart, getCompilerVersion } from './staticAnalysisCommon'
getFunctionDefinitionReturnParameterPart, getCompilerVersion
} from './staticAnalysisCommon'
import { AstWalker } from '@remix-project/remix-astwalker'
import { FunctionDefinitionAstNode, ParameterListAstNode, ModifierDefinitionAstNode, ContractHLAst, VariableDeclarationAstNode,
FunctionHLAst, ReportObj, ReportFunction, VisitFunction, ModifierHLAst, CompilationResult } from '../../types'
import {
FunctionDefinitionAstNode, ParameterListAstNode, ModifierDefinitionAstNode, ContractHLAst, VariableDeclarationAstNode,
FunctionHLAst, ReportObj, ReportFunction, VisitFunction, ModifierHLAst, CompilationResult
} from '../../types'
type WrapFunction = ((contracts: ContractHLAst[], isSameName: boolean, version: string) => ReportObj[])
......@@ -23,7 +27,7 @@ export default class abstractAstView {
*/
multipleContractsWithSameName = false
/**
/**
* Builds a higher level AST view. I creates a list with each contract as an object in it.
* Example contractsOut:
*
......@@ -48,9 +52,10 @@ export default class abstractAstView {
* @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.
*/
// eslint-disable-next-line camelcase
build_visit (relevantNodeFilter: ((node:any) => boolean)): VisitFunction {
return (node: any) => {
if (node.nodeType === "ContractDefinition") {
if (node.nodeType === 'ContractDefinition') {
this.setCurrentContract({
node: node,
functions: [],
......@@ -59,11 +64,11 @@ export default class abstractAstView {
inheritsFrom: [],
stateVariables: getStateVariableDeclarationsFromContractNode(node)
})
} else if (node.nodeType === "InheritanceSpecifier") {
} else if (node.nodeType === 'InheritanceSpecifier') {
const currentContract: ContractHLAst = this.getCurrentContract()
const inheritsFromName: string = getInheritsFromName(node)
currentContract.inheritsFrom.push(inheritsFromName)
} else if (node.nodeType === "FunctionDefinition") {
} else if (node.nodeType === 'FunctionDefinition') {
this.setCurrentFunction({
node: node,
relevantNodes: [],
......@@ -78,14 +83,14 @@ export default class abstractAstView {
this.getCurrentFunction().relevantNodes.push(item.node)
}
})
} else if (node.nodeType === "ModifierDefinition") {
} else if (node.nodeType === 'ModifierDefinition') {
this.setCurrentModifier({
node: node,
relevantNodes: [],
localVariables: this.getLocalVariables(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.')
this.getCurrentFunction().modifierInvocations.push(node)
} else if (relevantNodeFilter(node)) {
......@@ -102,6 +107,7 @@ export default class abstractAstView {
}
}
// eslint-disable-next-line camelcase
build_report (wrap: WrapFunction): ReportFunction {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return (compilationResult: CompilationResult) => {
......@@ -176,7 +182,7 @@ export default class abstractAstView {
private getLocalVariables (funcNode: ParameterListAstNode): VariableDeclarationAstNode[] {
const locals: VariableDeclarationAstNode[] = []
new AstWalker().walkFull(funcNode, (node: any) => {
if (node.nodeType === "VariableDeclaration") locals.push(node)
if (node.nodeType === 'VariableDeclaration') locals.push(node)
return true
})
return locals
......
import { default as category } from './categories'
import category from './categories'
import { isSubScopeWithTopLevelUnAssignedBinOp, getUnAssignedTopLevelBinOps } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, BlockAstNode, IfStatementAstNode,
WhileStatementAstNode, ForStatementAstNode, CompilationResult, ExpressionStatementAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, BlockAstNode, IfStatementAstNode,
WhileStatementAstNode, ForStatementAstNode, CompilationResult, ExpressionStatementAstNode, SupportedVersion
} from './../../types'
export default class assignAndCompare implements AnalyzerModule {
warningNodes: ExpressionStatementAstNode[] = []
name = `Result not used: `
description = `The result of an operation not used`
name = 'Result not used: '
description = 'The result of an operation not used'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......
import { default as category } from './categories'
import category from './categories'
import { isBlockBlockHashAccess } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion } from './../../types'
export default class blockBlockhash implements AnalyzerModule {
warningNodes: FunctionCallAstNode[] = []
name = `Block hash: `
description = `Can be influenced by miners`
name = 'Block hash: '
description = 'Can be influenced by miners'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -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 { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, IdentifierAstNode,
MemberAccessAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, IdentifierAstNode,
MemberAccessAstNode, SupportedVersion
} from './../../types'
export default class blockTimestamp implements AnalyzerModule {
warningNowNodes: IdentifierAstNode[] = []
warningblockTimestampNodes: MemberAccessAstNode[] = []
name = `Block timestamp: `
description = `Can be influenced by miners`
name = 'Block timestamp: '
description = 'Can be influenced by miners'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
start: '0.4.12'
}
visit (node: IdentifierAstNode | MemberAccessAstNode ): void {
if (node.nodeType === "Identifier" && isNowAccess(node)) this.warningNowNodes.push(node)
else if (node.nodeType === "MemberAccess" && isBlockTimestampAccess(node)) this.warningblockTimestampNodes.push(node)
visit (node: IdentifierAstNode | MemberAccessAstNode): void {
if (node.nodeType === 'Identifier' && isNowAccess(node)) this.warningNowNodes.push(node)
else if (node.nodeType === 'MemberAccess' && isBlockTimestampAccess(node)) this.warningblockTimestampNodes.push(node)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
......
export default {
SECURITY: {displayName: 'Security', id: 'SEC'},
GAS: {displayName: 'Gas & Economy', id: 'GAS'},
MISC: {displayName: 'Miscellaneous', id: 'MISC'},
ERC: {displayName: 'ERC', id: 'ERC'}
SECURITY: { displayName: 'Security', id: 'SEC' },
GAS: { displayName: 'Gas & Economy', id: 'GAS' },
MISC: { displayName: 'Miscellaneous', id: 'MISC' },
ERC: { displayName: 'ERC', id: 'ERC' }
}
import { default as category } from './categories'
import { isInteraction, isEffect, isLocalCallGraphRelevantNode, getFullQuallyfiedFuncDefinitionIdent,
isWriteOnStateVariable, isStorageVariableDeclaration, getFullQualifiedFunctionCallIdent, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import {
isInteraction, isEffect, isLocalCallGraphRelevantNode, getFullQuallyfiedFuncDefinitionIdent,
isWriteOnStateVariable, isStorageVariableDeclaration, getFullQualifiedFunctionCallIdent, getCompilerVersion
} from './staticAnalysisCommon'
import algorithm from './algorithmCategories'
import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph'
import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VariableDeclarationAstNode,
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VariableDeclarationAstNode,
FunctionHLAst, ContractCallGraph, Context, FunctionCallAstNode, AssignmentAstNode, UnaryOperationAstNode,
InlineAssemblyAstNode, ReportFunction, VisitFunction, FunctionCallGraph, SupportedVersion } from './../../types'
InlineAssemblyAstNode, ReportFunction, VisitFunction, FunctionCallGraph, SupportedVersion
} from './../../types'
export default class checksEffectsInteraction implements AnalyzerModule {
name = `Check-effects-interaction: `
description = `Potential reentrancy bugs`
name = 'Check-effects-interaction: '
description = 'Potential reentrancy bugs'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.HEURISTIC
version: SupportedVersion = {
......@@ -50,7 +54,7 @@ export default class checksEffectsInteraction implements AnalyzerModule {
comments += (multipleContractsWithSameName) ? 'Note: Import aliases are currently not supported by this static analysis.' : ''
warnings.push({
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`
})
}
......@@ -92,4 +96,3 @@ export default class checksEffectsInteraction implements AnalyzerModule {
return analyseCallGraph(context.callGraph, startFuncName, context, (node: any, context: Context) => isWriteOnStateVariable(node, context.stateVariables))
}
}
import { default as category } from './categories'
import { isLowLevelCall, isTransfer, isExternalDirectCall, isEffect, isLocalCallGraphRelevantNode, isSelfdestructCall,
import category from './categories'
import {
isLowLevelCall, isTransfer, isExternalDirectCall, isEffect, isLocalCallGraphRelevantNode, isSelfdestructCall,
isDeleteUnaryOperation, isPayableFunction, isConstructor, getFullQuallyfiedFuncDefinitionIdent, hasFunctionBody,
isConstantFunction, isWriteOnStateVariable, isStorageVariableDeclaration, isCallToNonConstLocalFunction,
getFullQualifiedFunctionCallIdent} from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
getFullQualifiedFunctionCallIdent
} from './staticAnalysisCommon'
import algorithm from './algorithmCategories'
import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph'
import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractCallGraph, Context, ContractHLAst,
FunctionHLAst, VariableDeclarationAstNode, FunctionCallGraph, FunctionCallAstNode, VisitFunction, ReportFunction, SupportedVersion} from './../../types'
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractCallGraph, Context, ContractHLAst,
FunctionHLAst, VariableDeclarationAstNode, FunctionCallGraph, FunctionCallAstNode, VisitFunction, ReportFunction, SupportedVersion
} from './../../types'
export default class constantFunctions implements AnalyzerModule {
name = `Constant/View/Pure functions: `
description = `Potentially constant/view/pure functions`
name = 'Constant/View/Pure functions: '
description = 'Potentially constant/view/pure functions'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.HEURISTIC
version: SupportedVersion = {
......@@ -26,8 +30,8 @@ export default class constantFunctions implements AnalyzerModule {
isExternalDirectCall(node) ||
isEffect(node) ||
isLocalCallGraphRelevantNode(node) ||
node.nodeType === "InlineAssembly" ||
node.nodeType === "NewExpression" ||
node.nodeType === 'InlineAssembly' ||
node.nodeType === 'NewExpression' ||
isSelfdestructCall(node) ||
isDeleteUnaryOperation(node)
)
......@@ -67,13 +71,13 @@ export default class constantFunctions implements AnalyzerModule {
if (func['potentiallyshouldBeConst']) {
warnings.push({
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`
})
} else {
warnings.push({
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`
})
}
......@@ -101,8 +105,8 @@ export default class constantFunctions implements AnalyzerModule {
isTransfer(node) ||
this.isCallOnNonConstExternalInterfaceFunction(node, context) ||
isCallToNonConstLocalFunction(node) ||
node.nodeType === "InlineAssembly" ||
node.nodeType === "NewExpression" ||
node.nodeType === 'InlineAssembly' ||
node.nodeType === 'NewExpression' ||
isSelfdestructCall(node) ||
isDeleteUnaryOperation(node)
}
......
import { default as category } from './categories'
import category from './categories'
import { isDeleteOfDynamicArray, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion } from './../../types'
export default class deleteDynamicArrays implements AnalyzerModule {
rel: UnaryOperationAstNode[] = []
name = `Delete dynamic array: `
description = `Use require/assert to ensure complete deletion`
name = 'Delete dynamic array: '
description = 'Use require/assert to ensure complete deletion'
category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -22,7 +22,7 @@ export default class deleteDynamicArrays implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts)
return this.rel.map((node) => {
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,
more: `https://solidity.readthedocs.io/en/${version}/types.html#delete`
}
......
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import algorithm from './algorithmCategories'
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 {
relevantNodes: UnaryOperationAstNode[] = []
name = `Delete from dynamic array: `
description = `'delete' leaves a gap in array`
name = 'Delete from dynamic array: '
description = '\'delete\' leaves a gap in array'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -21,7 +21,7 @@ export default class deleteFromDynamicArray implements AnalyzerModule {
report (compilationResults: CompilationResult): ReportObj[] {
return this.relevantNodes.map((node) => {
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,
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 { default as algorithm } from './algorithmCategories'
import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, VisitFunction, ReportFunction, ContractHLAst,
FunctionHLAst, VariableDeclarationAstNode, SupportedVersion} from './../../types'
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, VisitFunction, ReportFunction, ContractHLAst,
FunctionHLAst, VariableDeclarationAstNode, SupportedVersion
} from './../../types'
export default class erc20Decimals implements AnalyzerModule {
name = `ERC20: `
description = `'decimals' should be 'uint8'`
name = 'ERC20: '
description = '\'decimals\' should be \'uint8\''
category: ModuleCategory = category.ERC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -38,7 +40,7 @@ export default class erc20Decimals implements AnalyzerModule {
if (decimalsVar.length > 0) {
for (const node of decimalsVar) {
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,
more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals'
})
......@@ -46,7 +48,7 @@ export default class erc20Decimals implements AnalyzerModule {
} else if (decimalsFun.length > 0) {
for (const fn of decimalsFun) {
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,
more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals'
})
......@@ -66,4 +68,3 @@ export default class erc20Decimals implements AnalyzerModule {
funSignatures.includes('allowance(address,address)')
}
}
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import algorithm from './algorithmCategories'
import { isLoop, isTransfer, getCompilerVersion } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode,
WhileStatementAstNode, ExpressionStatementAstNode, SupportedVersion} from './../../types'
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode,
WhileStatementAstNode, ExpressionStatementAstNode, SupportedVersion
} from './../../types'
export default class etherTransferInLoop implements AnalyzerModule {
relevantNodes: ExpressionStatementAstNode[] = []
name = `Ether transfer in loop: `
description = `Transferring Ether in a for/while/do-while loop`
name = 'Ether transfer in loop: '
description = 'Transferring Ether in a for/while/do-while loop'
category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -16,13 +18,14 @@ export default class etherTransferInLoop implements AnalyzerModule {
visit (node: ForStatementAstNode | WhileStatementAstNode): void {
let transferNodes: ExpressionStatementAstNode[] = []
if(isLoop(node)) {
if(node.body && node.body.nodeType === 'Block')
transferNodes = node.body.statements.filter(child => ( child.nodeType === 'ExpressionStatement' &&
child.expression.nodeType === 'FunctionCall' && isTransfer(child.expression.expression)))
if (isLoop(node)) {
if (node.body && node.body.nodeType === 'Block') {
transferNodes = node.body.statements.filter(child =>
(child.nodeType === 'ExpressionStatement' &&
child.expression.nodeType === 'FunctionCall' &&
isTransfer(child.expression.expression)))
} else if (node.body && node.body.nodeType === 'ExpressionStatement' && node.body.expression.nodeType === 'FunctionCall' && isTransfer(node.body.expression.expression)) { transferNodes.push(node.body) }
// When loop body is described without braces
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) {
this.relevantNodes.push(...transferNodes)
}
......@@ -34,7 +37,7 @@ export default class etherTransferInLoop implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts)
return this.relevantNodes.map((node) => {
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,
more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops`
}
......
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import algorithm from './algorithmCategories'
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 {
relevantNodes: ForStatementAstNode[] = []
name = `For loop over dynamic array: `
description = `Iterations depend on dynamic array's size`
name = 'For loop over dynamic array: '
description = 'Iterations depend on dynamic array\'s size'
category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -16,9 +16,9 @@ export default class forLoopIteratesOverDynamicArray implements AnalyzerModule {
visit (node: ForStatementAstNode): void {
const { condition } = node
// 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`
(condition && condition.nodeType === "BinaryOperation" && isDynamicArrayLengthAccess(condition.rightExpression))) {
(condition && condition.nodeType === 'BinaryOperation' && isDynamicArrayLengthAccess(condition.rightExpression))) {
this.relevantNodes.push(node)
}
}
......@@ -28,7 +28,7 @@ export default class forLoopIteratesOverDynamicArray implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts)
return this.relevantNodes.map((node) => {
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,
more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops`
}
......
'use strict'
import { FunctionHLAst, ContractHLAst, FunctionCallGraph, ContractCallGraph, Context, FunctionCallAstNode } from "../../types"
import { isLocalCallGraphRelevantNode, isExternalDirectCall, getFullQualifiedFunctionCallIdent,
getFullQuallyfiedFuncDefinitionIdent, getContractName } from './staticAnalysisCommon'
import { FunctionHLAst, ContractHLAst, FunctionCallGraph, ContractCallGraph, Context, FunctionCallAstNode } from '../../types'
import {
isLocalCallGraphRelevantNode, isExternalDirectCall, getFullQualifiedFunctionCallIdent,
getFullQuallyfiedFuncDefinitionIdent, getContractName
} from './staticAnalysisCommon'
type filterNodesFunction = (node: FunctionCallAstNode) => boolean
type NodeIdentFunction = (node: FunctionCallAstNode) => 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> = {}
functions.forEach((func: FunctionHLAst) => {
const calls: string[] = func.relevantNodes
......@@ -108,6 +110,5 @@ function resolveCallGraphSymbolInternal (callGraph: Record<string, ContractCallG
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 !== null)
return current
if (current !== null) { return current }
}
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import algorithm from './algorithmCategories'
import { getFunctionDefinitionName, helpers, isVariableTurnedIntoGetter, getMethodParamsSplittedTypeDesc } from './staticAnalysisCommon'
import { ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, CompiledContract, AnalyzerModule,
FunctionDefinitionAstNode, VariableDeclarationAstNode, SupportedVersion } from './../../types'
import {
ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, CompiledContract, AnalyzerModule,
FunctionDefinitionAstNode, VariableDeclarationAstNode, SupportedVersion
} from './../../types'
export default class gasCosts implements AnalyzerModule {
name = `Gas costs: `
description = `Too high gas requirement of functions`
name = 'Gas costs: '
description = 'Too high gas requirement of functions'
category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -16,20 +18,17 @@ export default class gasCosts implements AnalyzerModule {
warningNodes: any[] = []
visit (node: FunctionDefinitionAstNode | VariableDeclarationAstNode): void {
if ((node.nodeType === 'FunctionDefinition' && node.kind !== 'constructor' && node.implemented) ||
(node.nodeType === 'VariableDeclaration' && isVariableTurnedIntoGetter(node)))
this.warningNodes.push(node)
(node.nodeType === 'VariableDeclaration' && isVariableTurnedIntoGetter(node))) { this.warningNodes.push(node) }
}
report (compilationResults: CompilationResult): ReportObj[] {
const report: ReportObj[] = []
const methodsWithSignature: Record<string, string>[] = this.warningNodes.map(node => {
let signature: string;
if(node.nodeType === 'FunctionDefinition'){
let signature: string
if (node.nodeType === 'FunctionDefinition') {
const functionName: string = getFunctionDefinitionName(node)
signature = helpers.buildAbiSignature(functionName, getMethodParamsSplittedTypeDesc(node, compilationResults.contracts))
}
else
signature = node.name + '()'
} else { signature = node.name + '()' }
return {
name: node.name,
......@@ -42,8 +41,8 @@ export default class gasCosts implements AnalyzerModule {
for (const contractName in compilationResults.contracts[filename]) {
const contract: CompiledContract = compilationResults.contracts[filename][contractName]
const methodGas: Record<string, any> | undefined = this.checkMethodGas(contract, method.signature)
if(methodGas && methodGas.isInfinite) {
if(methodGas.isFallback) {
if (methodGas && methodGas.isInfinite) {
if (methodGas.isFallback) {
report.push({
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.`,
......@@ -65,9 +64,9 @@ export default class gasCosts implements AnalyzerModule {
return report
}
private checkMethodGas(contract: CompiledContract, methodSignature: string): Record<string, any> | undefined {
if(contract.evm && contract.evm.gasEstimates && contract.evm.gasEstimates.external) {
if(methodSignature === '()') {
private checkMethodGas (contract: CompiledContract, methodSignature: string): Record<string, any> | undefined {
if (contract.evm && contract.evm.gasEstimates && contract.evm.gasEstimates.external) {
if (methodSignature === '()') {
const fallback: string = contract.evm.gasEstimates.external['']
if (fallback !== undefined && (fallback === null || parseInt(fallback) >= 2100 || fallback === 'infinite')) {
return {
......
import { default as category } from './categories'
import category from './categories'
import { isRequireCall, isAssertCall, getCompilerVersion } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion } from './../../types'
export default class guardConditions implements AnalyzerModule {
guards: FunctionCallAstNode[] = []
name = `Guard conditions: `
description = `Ensure appropriate use of require/assert`
name = 'Guard conditions: '
description = 'Ensure appropriate use of require/assert'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -22,7 +22,7 @@ export default class guardConditions implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts)
return this.guards.map((node) => {
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,
more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#error-handling-assert-require-revert-and-exceptions`
}
......
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, InlineAssemblyAstNode, SupportedVersion} from './../../types'
import category from './categories'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, InlineAssemblyAstNode, SupportedVersion } from './../../types'
import { getCompilerVersion } from './staticAnalysisCommon'
export default class inlineAssembly implements AnalyzerModule {
inlineAssNodes: InlineAssemblyAstNode[] = []
name = `Inline assembly: `
description = `Inline assembly used`
name = 'Inline assembly: '
description = 'Inline assembly used'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -14,7 +14,7 @@ export default class inlineAssembly implements AnalyzerModule {
}
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
......
import { default as category } from './categories'
import category from './categories'
import { isIntDivision } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, BinaryOperationAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, BinaryOperationAstNode, SupportedVersion } from './../../types'
export default class intDivisionTruncate implements AnalyzerModule {
warningNodes: BinaryOperationAstNode[] = []
name = `Data truncated: `
description = `Division on int/uint values truncates the result`
name = 'Data truncated: '
description = 'Division on int/uint values truncates the result'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
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 { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types'
interface llcNode {
node: MemberAccessAstNode
......@@ -10,8 +10,8 @@ interface llcNode {
export default class lowLevelCalls implements AnalyzerModule {
llcNodes: llcNode[] = []
name = `Low level calls: `
description = `Should only be used by experienced devs`
name = 'Low level calls: '
description = 'Should only be used by experienced devs'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -20,19 +20,19 @@ export default class lowLevelCalls implements AnalyzerModule {
visit (node : MemberAccessAstNode): void {
if (isLLCall(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.CALL})
this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALL })
} else if (isLLDelegatecall(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.DELEGATECALL})
this.llcNodes.push({ node: node, type: lowLevelCallTypes.DELEGATECALL })
} else if (isLLSend(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.SEND})
this.llcNodes.push({ node: node, type: lowLevelCallTypes.SEND })
} else if (isLLDelegatecall04(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.DELEGATECALL})
this.llcNodes.push({ node: node, type: lowLevelCallTypes.DELEGATECALL })
} else if (isLLSend04(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.SEND})
this.llcNodes.push({ node: node, type: lowLevelCallTypes.SEND })
} else if (isLLCall04(node)) {
this.llcNodes.push({node: node, type: lowLevelCallTypes.CALL})
this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALL })
} 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 {
})
}
}
import { default as category } from './categories'
import category from './categories'
import { hasFunctionBody, getFullQuallyfiedFuncDefinitionIdent, getEffectedVariableName } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst,
VisitFunction, ReportFunction, ReturnAstNode, AssignmentAstNode, SupportedVersion} from './../../types'
import {
AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst,
VisitFunction, ReportFunction, ReturnAstNode, AssignmentAstNode, SupportedVersion
} from './../../types'
export default class noReturn implements AnalyzerModule {
name = `No return: `
description = `Function with 'returns' not returning`
name = 'No return: '
description = 'Function with \'returns\' not returning'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -17,7 +19,7 @@ export default class noReturn implements AnalyzerModule {
abstractAst: AbstractAst = new AbstractAst()
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))
......@@ -30,12 +32,12 @@ export default class noReturn implements AnalyzerModule {
if (this.hasNamedAndUnnamedReturns(func)) {
warnings.push({
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)))) {
warnings.push({
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 {
}
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 {
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))
return diff.length === 0
}
......
import { default as category } from './categories'
import category from './categories'
import { isStatement, isSelfdestructCall } from './staticAnalysisCommon'
import { default as algorithm } from './algorithmCategories'
import algorithm from './algorithmCategories'
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 {
name = `Selfdestruct: `
description = `Contracts using destructed contract can be broken`
name = 'Selfdestruct: '
description = 'Contracts using destructed contract can be broken'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.HEURISTIC
version: SupportedVersion = {
......@@ -16,7 +16,7 @@ export default class selfdestruct implements AnalyzerModule {
abstractAst: AbstractAst = new AbstractAst()
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))
......@@ -30,7 +30,7 @@ export default class selfdestruct implements AnalyzerModule {
func.relevantNodes.forEach((node) => {
if (isSelfdestructCall(node)) {
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,
more: 'https://paritytech.io/blog/security-alert.html'
})
......@@ -38,7 +38,7 @@ export default class selfdestruct implements AnalyzerModule {
}
if (isStatement(node) && hasSelf) {
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,
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 { default as algorithm } from './algorithmCategories'
import algorithm from './algorithmCategories'
import AbstractAst from './abstractAstView'
import { get } from 'fast-levenshtein'
import { util } from '@remix-project/remix-lib'
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 {
var1: string
......@@ -14,8 +14,8 @@ interface SimilarRecord {
}
export default class similarVariableNames implements AnalyzerModule {
name = `Similar variable names: `
description = `Variable names are too similar`
name = 'Similar variable names: '
description = 'Variable names are too similar'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -47,17 +47,17 @@ export default class similarVariableNames implements AnalyzerModule {
const vars: string[] = this.getFunctionVariables(contract, func).map(getDeclaredVariableName)
this.findSimilarVarNames(vars).map((sim) => {
// check if function is implemented
if(func.node.implemented) {
if (func.node.implemented) {
const astWalker = new AstWalker()
const functionBody: any = func.node.body
// Walk through all statements of function
astWalker.walk(functionBody, (node) => {
// check if these is an identifier node which is one of the tracked similar variables
if ((node.nodeType === 'Identifier' || node.nodeType === 'VariableDeclaration')
&& (node.name === sim.var1 || node.name === sim.var2)) {
if ((node.nodeType === 'Identifier' || node.nodeType === 'VariableDeclaration') &&
(node.name === sim.var1 || node.name === sim.var2)) {
warnings.push({
warning: `${funcName} : Variables have very similar names "${sim.var1}" and "${sim.var2}". ${hasModifiersComments} ${multipleContractsWithSameNameComments}`,
location: node['src']
location: node.src
})
}
return true
......
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import algorithm from './algorithmCategories'
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 {
name = `String length: `
description = `Bytes length != String length`
name = 'String length: '
description = 'Bytes length != String length'
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -16,8 +16,8 @@ export default class stringBytesLength implements AnalyzerModule {
bytesLengthChecks: MemberAccessAstNode[] = []
visit (node: FunctionCallAstNode | MemberAccessAstNode): void {
if (node.nodeType === "FunctionCall" && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node)
else if (node.nodeType === "MemberAccess" && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node)
if (node.nodeType === 'FunctionCall' && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node)
else if (node.nodeType === 'MemberAccess' && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
......@@ -25,7 +25,7 @@ export default class stringBytesLength implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts)
if (this.stringToBytesConversions.length > 0 && this.bytesLengthChecks.length > 0) {
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,
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 { default as algorithm } from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types'
import algorithm from './algorithmCategories'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types'
export default class thisLocal implements AnalyzerModule {
warningNodes: MemberAccessAstNode[] = []
name = `This on local calls: `
description = `Invocation of local functions via 'this'`
name = 'This on local calls: '
description = 'Invocation of local functions via \'this\''
category: ModuleCategory = category.GAS
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -22,7 +22,7 @@ export default class thisLocal implements AnalyzerModule {
const version = getCompilerVersion(compilationResults.contracts)
return this.warningNodes.map(function (item, i) {
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,
more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#external-function-calls`
}
......
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import category from './categories'
import algorithm from './algorithmCategories'
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 {
txOriginNodes: MemberAccessAstNode[] = []
name = `Transaction origin: `
description = `'tx.origin' used`
name = 'Transaction origin: '
description = '\'tx.origin\' used'
category: ModuleCategory = category.SECURITY
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
......@@ -15,7 +15,6 @@ export default class txOrigin implements AnalyzerModule {
visit (node: MemberAccessAstNode): void {
if (isTxOriginAccess(node)) this.txOriginNodes.push(node)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
......
......@@ -121,9 +121,9 @@ export interface ContractCallGraph {
functions: Record<string, FunctionCallGraph>
}
/////////////////////////////////////////////////////////////
///////////// Specfic AST Nodes /////////////////////////////
/////////////////////////////////////////////////////////////
/// //////////////////////////////////////////////////////////
/// ////////// Specfic AST Nodes /////////////////////////////
/// //////////////////////////////////////////////////////////
interface TypeDescription {
typeIdentifier: string
......@@ -629,10 +629,9 @@ export interface CommonAstNode {
[x: string]: any
}
/////////////////////////////////////////////////////////
///////////// YUL AST Nodes /////////////////////////////
/////////////////////////////////////////////////////////
/// //////////////////////////////////////////////////////
/// ////////// YUL AST Nodes /////////////////////////////
/// //////////////////////////////////////////////////////
export interface YulTypedNameAstNode {
name: string
......@@ -674,12 +673,11 @@ export interface CommonYulAstNode {
[x: string]: any
}
/// ////////
// ERROR //
/// ////////
///////////
// ERROR //
///////////
export interface CompilationError {
export interface CompilationError {
/** Location within the source file */
sourceLocation?: {
file: string
......@@ -712,20 +710,20 @@ export interface CommonYulAstNode {
| 'FatalError'
| 'Warning'
////////////
// SOURCE //
////////////
export interface CompilationSource {
/// /////////
// SOURCE //
/// /////////
export interface CompilationSource {
/** Identifier of the source (used in source maps) */
id: number
/** The AST object */
ast: AstNode
}
/////////
// AST //
/////////
export interface AstNode {
/// //////
// AST //
/// //////
export interface AstNode {
absolutePath?: string
exportedSymbols?: Record<string, unknown>
id: number
......@@ -740,7 +738,7 @@ export interface CommonYulAstNode {
[x: string]: any
}
export interface AstNodeAtt {
export interface AstNodeAtt {
operator?: string
string?: null
type?: string
......@@ -754,10 +752,10 @@ export interface CommonYulAstNode {
[x: string]: any
}
//////////////
// CONTRACT //
//////////////
export interface CompiledContract {
/// ///////////
// CONTRACT //
/// ///////////
export interface CompiledContract {
/** The Ethereum Contract ABI. If empty, it is represented as an empty array. */
abi: ABIDescription[]
// See the Metadata Output documentation (serialised JSON string)
......@@ -803,12 +801,12 @@ export interface CommonYulAstNode {
}
}
/////////
// ABI //
/////////
export type ABIDescription = FunctionDescription | EventDescription
/// //////
// ABI //
/// //////
export type ABIDescription = FunctionDescription | EventDescription
export interface FunctionDescription {
export interface FunctionDescription {
/** Type of the method. default is 'function' */
type?: 'function' | 'constructor' | 'fallback' | 'receive'
/** The name of the function. Constructor and fallback function never have name */
......@@ -825,7 +823,7 @@ export interface CommonYulAstNode {
constant?: boolean
}
export interface EventDescription {
export interface EventDescription {
type: 'event'
name: string
inputs: ABIParameter &
......@@ -837,7 +835,7 @@ export interface CommonYulAstNode {
anonymous: boolean
}
export interface ABIParameter {
export interface ABIParameter {
internalType: string
/** The name of the parameter */
name: string
......@@ -847,7 +845,7 @@ export interface CommonYulAstNode {
components?: ABIParameter[]
}
export type ABITypeParameter =
export type ABITypeParameter =
| 'uint'
| 'uint[]' // TODO : add <M>
| 'int'
......@@ -868,38 +866,38 @@ export interface CommonYulAstNode {
| 'tuple[]'
| string // Fallback
///////////////////////////
// NATURAL SPECIFICATION //
///////////////////////////
/// ////////////////////////
// NATURAL SPECIFICATION //
/// ////////////////////////
// Userdoc
export interface UserDocumentation {
// Userdoc
export interface UserDocumentation {
methods: UserMethodList
notice: string
}
export type UserMethodList = {
export type UserMethodList = {
[functionIdentifier: string]: UserMethodDoc
} & {
'constructor'?: string
}
export interface UserMethodDoc {
export interface UserMethodDoc {
notice: string
}
// Devdoc
export interface DeveloperDocumentation {
// Devdoc
export interface DeveloperDocumentation {
author: string
title: string
details: string
methods: DevMethodList
}
export interface DevMethodList {
export interface DevMethodList {
[functionIdentifier: string]: DevMethodDoc
}
export interface DevMethodDoc {
export interface DevMethodDoc {
author: string
details: string
return: string
......@@ -908,10 +906,10 @@ export interface CommonYulAstNode {
}
}
//////////////
// BYTECODE //
//////////////
export interface BytecodeObject {
/// ///////////
// BYTECODE //
/// ///////////
export interface BytecodeObject {
/** The bytecode as a hex string. */
object: string
/** Opcodes list */
......
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