Solidity Security Practices Part IV: Formal Verification

By akohad Mar23,2023

[ad_1]

What is Formal Verification?

Approaches to Formal Verification in Solidity

1. Bounded Model Checking

contract Voting {
mapping(address => bool) public hasVoted;
uint public yesVotes;
uint public noVotes;
function vote(bool voteYes) public {
require(!hasVoted[msg.sender]);
if (voteYes) {
yesVotes++;
} else {
noVotes++;
}
hasVoted[msg.sender] = true;
}
}
$ myth analyze Voting.sol --execution-timeout 120

2. Theorem Proving

contract Adder {
function add(uint a, uint b) public pure returns (uint) {
uint c = a + b;
return c;
}
}
rule <k> add(a:UInt, b:UInt) => c:UInt
requires true
ensures c == a + b
</k>
$ kprove add.k

Examples of Formal Verification in Solidity

Example 1: Reentrancy Vulnerability Detection using Mythril

contract Bank {
mapping(address => uint) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint amount) public {
require(amount <= balances[msg.sender]);
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
balances[msg.sender] -= amount;
}
}
$ myth analyze Bank.sol --execution-timeout 120 --truffle

Example 2: Smart Contract Verification using the K Framework

contract Voting {
mapping(address => bool) public hasVoted;
uint public yesVotes;
uint public noVotes;
function vote(bool voteYes) public {
require(!hasVoted[msg.sender]);
if (voteYes) {
yesVotes++;
} else {
noVotes++;
}
hasVoted[msg.sender] = true;
}
}
rule <k> vote(hv:Map, yv:UInt, nv:UInt, v:Address, b:Bool) => hv':Map, yv':UInt, nv':UInt
requires !hv
$ kprove vote.k

Final Words

Join Coinmonks Telegram Channel and Youtube Channel get daily Crypto News

[ad_2]

Source link

By akohad

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *