18.SWC-118_Constructor Name
2023-07-13 16:11:46 # 09.SWC

SWC-118_Constructor Name

Incorrect Constructor Name

  • Description: Constructors are special functions that are called only once during the contract creation. They often perform critical, privileged actions such as setting the owner of the contract. Before Solidity version 0.4.22, the only way of defining a constructor was to create a function with the same name as the contract class containing it. A function meant to become a constructor becomes a normal, callable function if its name doesn’t exactly match the contract name. This behavior sometimes leads to security issues, in particular when smart contract code is re-used with a different name but the name of the constructor function is not changed accordingly.

  • Remediation: Solidity version 0.4.22 introduces a new constructor keyword that make a constructor definitions clearer. It is therefore recommended to upgrade the contract to a recent version of the Solidity compiler and change to the new constructor declaration.

vulnerability contract 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
pragma solidity 0.4.24;

contract Missing{
address private owner;

modifier onlyowner {
require(msg.sender==owner);
_;
}

function missing() // 改成constructor
public
{
owner = msg.sender;
}

function () payable {}

function withdraw()
public
onlyowner
{
owner.transfer(this.balance);
}

vulnerability contract 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
pragma solidity 0.4.24;

contract Missing{
address private owner;

modifier onlyowner {
require(msg.sender==owner);
_;
}

function Constructor() // 改成constructor
public
{
owner = msg.sender;
}

function () payable {}

function withdraw()
public
onlyowner
{
owner.transfer(this.balance);
}

}
Prev
2023-07-13 16:11:46 # 09.SWC
Next