solidity: Any tools to generate the specific path in bytecode - solidity

I am studying smart contract detection tools. For the testing part, I only need the bytecode for the specific path. Here is the example
contract Suicide{
address public owner;
modifier onlyOwner{
if(msg.sender != owner) revert();
_;
}
function setOwner() public{
owner = msg.sender;
}
function kill(address addr) public onlyOwner{
selfdestruct(msg.sender);
}
}
The vulnerability is caused by setOwner() -> kill(). How can I get the bytecode of the function call?
To be more specific, the result(bytecode) is to put into Mythril for the symbolic execution.

Related

can msg.sender be spoofed in view function?

From what I can see, it seems trivially easy to set message sender in a view function to whatever address you want for external calls through ethers.js via the 'connect' function.
For example, if you have a contract like this:
contract Test {
address public owner;
string private secret;
modifier onlyOwner() {
require(msg.sender==owner,"onlyOwner");
_;
}
constructor() {
owner = msg.sender;
secret="Abracadabra";
}
function setSecret(string memory newSecret) public onlyOwner {
secret = newSecret;
}
function getSecret() public view onlyOwner returns(string memory) {
return secret;
}
}
Even if you aren't the owner account, you could run
let owner = await con.owner();
let secret = con.connect(owner).getSecret()
And get no complaints from ethers. I know this would fail if you tried to run setSecret but when there no transaction involved it looks like you don't need a real signer, just a contract address.
Is there some other to check if the msg.sender is actually an account, not just a string of the account address?
Sure it can be, it is not a 'hack', when you call view function you can overwrite msg.sender
And anyway 'secret' variable (even private) can be read by some tools, as any data on blockchain (even if you will not provide read function), it is not a security measure to make variable private..

I'm trying to test out a smart contract using Remix but "This contract may be abstract "is appeared

I'm trying to test out a smart contract using Remix.
They compile fine, but when I deploy thz contractenter code here I get this error:
This contract may be abstract, not implement an abstract parent's methods completely or not invoke an inherited contract's constructor correctly.
Anyone know what could be going on? Thanks!
pragma solidity ^0.8.7;
interface UDL_SC_lifecycle_manager {
struct TP {
uint id;
}
struct OP {
uint id;
}
struct BP{
uint id;
}
//ContractDescriptionMetaData
struct CDMD {
uint ID;
address providerAdress;
TP TechnicalPerspective;
OP OperationalPerspective;
BP BusnissPerspective;
}
function PublishDesc(CDMD memory ContractDescription, address provider) external ;
function UpdateDesc(CDMD memory ContractDescription, address provider) external ;
function DestroyDesc(address contractadr, uint contractID) external returns(bool);
}
abstract contract SmartRegistryService is UDL_SC_lifecycle_manager{
mapping(address => CDMD) CDMDS;
address contractAdresse;
address proprietaire;
event DescriptionPublished(string _msg);
event DescriptionUpdated (string _msg);
event NotExist (string _msg);
event Deleted (string _msg);
function publishdesc (CDMD memory NVContractDescriptionMetaData, address providerAdress) public {
CDMDS[providerAdress] = NVContractDescriptionMetaData;
emit DescriptionPublished(" smart contract published successfully!");
}
modifier ProviderOnly(address provider){
require(msg.sender == provider);
_;
}
function updatedesc (CDMD memory NVContractDescriptionMetaData, address providerAddress, uint contractID) public {
bool statue = false;
CDMD storage newContractDescriptionMetaData = CDMDS[providerAddress];
if((newContractDescriptionMetaData.ID== contractID)&&(newContractDescriptionMetaData.providerAdress == providerAddress)){
statue = true;
CDMDS[providerAddress] = NVContractDescriptionMetaData;
emit DescriptionUpdated("smart contract updated successfully!");
}else{
emit NotExist("smart contract notExist!");
}
}
function destroydesc(address providerAddress, uint contractID) public {
CDMD storage newContractDescriptionMetaData = CDMDS[providerAddress];
if (newContractDescriptionMetaData.ID == contractID) {
delete CDMDS[providerAddress];
emit Deleted("smart contract deleted successfully!");
}
}
}

Solidity: Are these sentences the same? Or do they mean different things?

In order to calling a function 'isContract', with the parameter 'to' being an address, are valid both ways? :
to.isContract()
isContract(to)
Does Solidity allow both ways?
I have found both in different codes, and I don't know if just 'isContract(to)' is the right one, or if 'to.isContract()' means another different thing.
Thanks a lot for your help.
They're not the same.
to.isContract() suggests that you have defined an interface (in your code) that defines a isContract() function, and that the contract deployed at the to address implements this interface.
pragma solidity ^0.8.0;
interface ExternalContract {
function isContract() external returns (bool);
}
contract MyContract {
function foo() external {
ExternalContract to = ExternalContract(address(0x123));
bool returnedValue = to.isContract(); // calling `to`'s function `isContract()`
}
}
isContract(to) calls an external or internal function in your contract.
pragma solidity ^0.8.0;
contract MyContract {
function foo() external {
address to = address(0x123);
bool returnedValue = isContract(to); // calling your function `isContract()`
}
function isContract(address to) internal returns (bool) {
return true;
}
}
Edit: I forgot about one more case - using a library containing the isContract() function for an address. Example OpenZeppelin implementation: definition, usage.
library AddressLibrary {
function isContract (address _address) {
return true;
}
}
contract MyContract {
using AddressLibrary for address;
function foo() external {
address to = address(0x123);
bool returnedValue to.isContract(); // calling your function `isContract(to)`
}

How to make an API call in solidity?

I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.
"example-winner.com/winner"
And it returns simple JSON with the address of the winner:
{"winner":"0xa7D0......."}
However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.
Any thoughts? Below is my code:
pragma solidity ^0.4.24;
contract LeagueWinners{
address public manager;
address[] public players;
uint256 MINIMUM = 1000000000000000;
constructor() public{
manager = msg.sender;
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
function getWinner() public{
assert(msg.sender == manager);
// TODO
// Get the winner from the API call
result = 0; // the result of the API call
players[result].transfer(address(this).balance);
// returns an adress object
// all units of transfer are in wei
players = new address[](0);
// this empties the dynamic array
}
}
You can use Chainlink as your Oracle.
As many have mentioned, you will need an oracle to get your API call. Something that is important to note, your contract is actually asking an oracle to make your API call for you, and not making the API call itself. This is because the blockchain is deterministic. For more information see this thread.
To answer your question, you can use the decentralized oracle service Chainlink.
You'd add a function:
function getWinner()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
For the purpose of the following exmaple, we are going to pretend you want to return a uint256 instead of an address. You can return a bytes32 and then convert it to an address, but for simplicity let's say the API returns the index of the winner. You'll have to find a node and jobId that can make a http.get request and return a uint256 object. You can find nodes and jobs from market.link. Each testnet (Ropsten, Mainnet, Kovan, etc) has different node addresses, so make sure you pick the right ones.
For this demo, we are going to use LinkPool's ropsten node
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
Ideally, you'd choose a number of nodes to run your job, to make it trustless and decentralized. You can read here for more information on precoordinators and aggregating data. disclosure I am the author of that blog
Your full contract would look like:
pragma solidity ^0.6.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
contract GetData is ChainlinkClient {
uint256 indexOfWinner;
address public manager;
address payable[] public players;
uint256 MINIMUM = 1000000000000000;
// The address of an oracle
address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
//bytes32 JOB= "93fedd3377a54d8dac6b4ceadd78ac34";
bytes32 JOB= "c179a8180e034cf5a341488406c32827";
uint256 ORACLE_PAYMENT = 1 * LINK;
constructor() public {
setPublicChainlinkToken();
manager = msg.sender;
}
function getWinnerAddress()
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);
req.add("get", "example-winner.com/winner");
req.add("path", "winner");
sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
}
// When the URL finishes, the response is routed to this function
function fulfill(bytes32 _requestId, uint256 _index)
public
recordChainlinkFulfillment(_requestId)
{
indexOfWinner = _index;
assert(msg.sender == manager);
players[indexOfWinner].transfer(address(this).balance);
players = new address payable[](0);
}
function enter() public payable{
assert(msg.value > MINIMUM);
players.push(msg.sender);
}
modifier onlyOwner() {
require(msg.sender == manager);
_;
}
// Allows the owner to withdraw their LINK on this contract
function withdrawLink() external onlyOwner() {
LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());
require(_link.transfer(msg.sender, _link.balanceOf(address(this))), "Unable to transfer");
}
}
This would do about everything you need.
If you can't adjust the API to return a uint, you can return a bytes32 and then convert it to an address or a string.
function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
You cannot. The vm does not have any I/O outside of the blockchain itself. Instead you will need to tell your smart contract who the winner is and then the smart contract can just read the value of that variable.
This design pattern is also known as the "oracle". Google "Ethereum oracle" for more info.
Basically your web server can call your smart contract. Your smart contract cannot call your web server. If you need your smart contract to access a 3rd party service then your web server will need to make the request then forward the result to solidity by calling a function in your smart contract.
You didn't properly explain what you are trying to do. Are you having trouble with the solidity code? or rather with your server? Here is an edited version. See if it helps.
pragma solidity ^0.4.24;
contract LeagueWinners{
address public manager;
//address[] public players;
uint256 MINIMUM = 1000000000000000;
constructor() public{
manager = msg.sender;
}
struct Player {
address playerAddress;
uint score;
}
Player[] public players;
// i prefer passing arguments this way
function enter(uint value) public payable{
assert(msg.value > MINIMUM);
players.push(Player(msg.sender, value));
}
//call this to get the address of winner
function winningPlayer() public view
returns (address winner)
{
uint winningScore = 0;
for (uint p = 0; p < players.length; p++) {
if (players[p].score > winningScore) {
winningScore = players[p].score;
winner = players[p].playerAddress;
}
}
}
// call this to transfer fund
function getWinner() public{
require(msg.sender == manager, "Only a manager is allowed to perform this operation");
// TODO
address winner = winningPlayer();
// Get the winner from the API call
//uint result = 0; // the result of the API call
winner.transfer(address(this).balance);
// returns an adress object
// all units of transfer are in wei
delete players;
// this empties the dynamic array
}
}
At least that is what I understand by your question.

Transfer ownership web3

I am creating a dapp to transfer ownership of the contract from one address to another using testrpc. However,I keep encountering this problem. I have tried using sentransaction method to do perform this ownership change.Perhaps I'm calling the exchange in a wrong manner.
Solidity version 0.4.4
web3 "version": "0.20.2"
web3.js:3127 Uncaught Error: VM Exception while processing transaction: invalid opcode
at Object.InvalidResponse (web3.js:3127)
at RequestManager.send (web3.js:6332)
at Eth.send [as sendTransaction] (web3.js:5066)
at SolidityFunction.sendTransaction (web3.js:4122)
at SolidityFunction.execute (web3.js:4208)
at transferOwnership (luxcure_manu.html:309)
at HTMLButtonElement.onclick (luxcure_manu.html:378
Full solidity contract as of yet.
pragma solidity ^0.4.4;
// TODO: Hash of the cert through IPFS Hash
// Transfer ownership of smart contract
contract LuxSecure {
address public contract_owner; //Manufacturer/owner
//string public current_owner; //Current Owner of good
bytes32 public model; //Model
mapping(uint => address) public owners; //list of owners
uint256 public owners_count;
bytes32 public status; // (Public(Owned by no one), Private(Bought by another entity),stolen(Stolen from public or private))
bytes32 public date_manufactured; //Time
// Set manufacturer of the Good RUN ONCE ONLY
function manufacturer() public{
if(owners_count == 0){
contract_owner = msg.sender;
}
}
//Modifier that only allows owner of the bag to Smart Contract AKA Good to use the function
modifier onlyOwner(){
require(msg.sender == contract_owner);
_;
}
// Add a new product to the blockchain with a new serial
function addNewGoods(bytes32 _model,bytes32 _status, bytes32 _date_manufactured) public returns(bool made) {//Declare Goods struct
setOwner(msg.sender);
model = _model;
status = _status;
date_manufactured = _date_manufactured;
return true;
}
//This function transfer ownership of contract from one entity to another
function transferOwnership(address _newOwner) public onlyOwner(){
require(_newOwner != address(0));
contract_owner = _newOwner;
}
//Set the KEY to uint256 and VALUE owner Ethereum Address
function setOwner(address owner)public{
owners_count += 1 ;
owners[owners_count] = owner;
}
//Get the previous owner in the mappings
function previousOwner()constant public returns(address){
if(owners_count != 0){
uint256 previous_owner = owners_count - 1;
return owners[previous_owner];
}
}
// Getter Methods
function getManufacturer() constant public returns(address){
return contract_owner;
}
function getCurrentOwner() constant public returns(address){
return owners[owners_count] ;
}
function getOwnerCount() constant public returns(uint256){
return owners_count;
}
function getModel() constant public returns(bytes32){
return model;
}
function getStatus() constant public returns(bytes32){
return status;
}
function getDateManufactured() constant public returns(bytes32){
return date_manufactured;
}
}// end of LuxSecure
Javascript to perform the transfer of ownership
function transferOwnership(){
var account_to_transfer = document.getElementById("ethereumaddress").value;
contract.transferOwnership(account_to_transfer,{
from:web3.eth.accounts[0],
gas:4000000
});
}
I don't see any particular mistake in your code. Maybe a bad formatting on the front-side, but can't guess for sure as we have partial front here.
I don't know if it will be some help but sometimes, using truffle, it happened to me to have some functions that returned bad opcode from testrpc/ganache-cli while no apparent error was in the code.
Deleting the ABI, recompiling the smart-contracts to get a brand new ABI and then redeploying the contracts solved the problem.