Access restriction

Access restriction is a solidity security pattern.  It only allows authorized parties to access certain functions. Due to the public nature of the blockchain, all data on the blockchain is visible to anyone. It is critical to declare your contract function, state with restricted access control, and provide security against unauthorized access to smart contract functionality.

pragma solidity ^0.4.24;
contract Ownable {
address owner;
uint public initTime = now;
constructor() public {
owner = msg.sender;
}
//check if the caller is the owner of the contract
modifier onlyOwner {
require(msg.sender == owner,"Only Owner Allowed." );
_;
}
//change the owner of the contract
//@param _newOwner the address of the new owner of the contract.
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
function getOwner() internal constant returns (address) {
return owner;
}
modifier onlyAfter(uint _time) {
require(now >= _time,"Function called too early.");
_;
}
modifier costs(uint _amount) {
require(msg.value >= _amount,"Not enough Ether provided." );
_;
if (msg.value > _amount)
msg.sender.transfer(msg.value - _amount);
}
}
contract SampleContarct is Ownable {


mapping(bytes32 => uint) myStorage;
constructor() public {
}
function getValue(bytes32 record) constant public returns (uint) {
return myStorage[record];
}
function setValue(bytes32 record, uint value) public onlyOwner {
myStorage[record] = value;
}
function forceOwnerChange(address _newOwner) public payable
onlyOwner onlyAfter(initTime + 2 weeks) costs(50 ether) {
owner =_newOwner;
initTime = now;
}
}

The preceding example shows the access restrict pattern applied  to a contract. We first define a parent class called Ownable with onlyOwner, changeOwner, and onlyAfter function modifiers.  Other contracts can inherit from this contract to use defined access restriction. SampleContract inherits from Ownable contract and therefore, only the owner can access setValue function. Furthermore,  forceOwnerChange may only be called two weeks after the contract creation time with 50 ether cost, and only the owner has permission to execute the function.  

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.124.49