Last active
November 15, 2017 02:18
-
-
Save libasoles/79824d6653e2e41325550e007e78a5d1 to your computer and use it in GitHub Desktop.
Solidity exercise: multi-signed contract
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.18; | |
/** | |
* All authorities must approved each defined action | |
* */ | |
contract MultiSignedContract { | |
address owner; | |
address[] authorities; | |
mapping (string => address[]) internal actions; | |
function MultiSignedContract() public { | |
owner = msg.sender; | |
authorities.push(owner); | |
} | |
function addAuthority(address user) public { | |
require(msg.sender == owner); | |
bool alreadyExists = false; | |
for(uint i = 0; i < authorities.length; i++) { | |
if(authorities[i] == user) { | |
alreadyExists = true; | |
} | |
} | |
if(!alreadyExists) { | |
authorities.push(user); | |
} | |
} | |
function addAction(string actionName) public returns(bool) { | |
require(msg.sender == owner); | |
if(actions[actionName].length == 0) { | |
actions[actionName].push(msg.sender); | |
return true; | |
} | |
return false; | |
} | |
event Approved(string actionName); | |
function approveAction(string actionName) public returns(int){ | |
// check action exists | |
if(actions[actionName].length == 0) { | |
return 0; | |
} | |
// sign | |
if(!userAlreadySigned(actionName, msg.sender)) { | |
actions[actionName].push(msg.sender); | |
return 1; | |
} | |
// emmit event if all authorities already signed | |
if(actionIsApproved(actionName)) { | |
Approved(actionName); | |
return 2; | |
} | |
} | |
function userAlreadySigned(string actionName, address user) public view returns(bool) { | |
for(uint i = 0; i < actions[actionName].length; i++) { | |
if(actions[actionName][i] == user) { | |
return true; | |
} | |
} | |
return false; | |
} | |
function actionIsApproved(string actionName) public view returns(bool) { | |
if(authorities.length == 0) { | |
return false; | |
} | |
uint i = 0; | |
bool approved = true; | |
do { | |
approved = approved && userAlreadySigned(actionName, authorities[i]); | |
i++; | |
} while( approved && i < authorities.length); | |
return approved; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment