Events for memory invalidations

Events for memory invalidations

library AVMMemoryContext32 {
    struct Context {
        uint256[] readAccesses;
        uint256[] writeAccesses;
        uint writeIdx;
        uint cachedRead;
        uint cachedReadValue;
        uint addressMask;
        uint addressMask32;
        uint addressMask256;
        bool valid;
    }

    event trace(string);
    event traceNum(uint);
    event MissingRead(uint);
    event BadWriteAddress(uint, uint);
    event BadWriteValue(uint, uint, uint);
    function initContext(uint256[] memory readAccesses, uint256[] memory writeAccesses, uint addressBits) internal returns (Context memory) {
        Context memory ctx;
        ctx.readAccesses = readAccesses;
        ctx.writeAccesses = writeAccesses;
        ctx.writeIdx = 0;
        ctx.addressMask = (2 ** addressBits) - 1;
        ctx.addressMask256 = ctx.addressMask ^ 31;
        ctx.addressMask32 = ctx.addressMask ^ 3;
        ctx.cachedRead = (uint) (-1);
        ctx.cachedReadValue = 0;
        ctx.valid = true;
        return ctx;
    }

    function read256(Context ctx, uint addr) internal returns (uint) {
        uint v;
        addr = addr & ctx.addressMask;

        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == (addr / 32)) {
                return ctx.readAccesses[i+1];
            }
        }

        ctx.valid = false;
        MissingRead(addr / 32);
        return 0;
    }

    function read32(Context ctx, uint addr) internal returns (uint32) {
        uint v = read256(ctx, addr);

        // Shift down to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            v = v / 4294967296;
        }

        return (uint32) (v);
    }

    function readByte(Context ctx, uint addr) internal returns (uint8) {
        uint32 v = read32(ctx, addr);

        for (uint j = (addr % 4); j < 3; j++) {
            v = v / 256;
        }

        return (uint8) (v);
    }

    function write256(Context ctx, uint addr, uint value) internal {
        addr = addr & ctx.addressMask;

        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
            ctx.valid = false;
            return;
        }

        // Whole overwrite - ignore prior value
        ctx.writeIdx++;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != value) {
            // Wrong write value
            BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
            ctx.valid = false;
            return;
        }

        trace("Updating read values for write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function write32(Context ctx, uint addr, uint value) internal {
        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]);
            ctx.valid = false;
            return;
        }

        trace("Reading write prior value");
        uint result = ctx.writeAccesses[ctx.writeIdx++];
        uint mask = 4294967295;
        value = value & mask;

        // Shift up to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            mask = mask * 4294967296;
            value = value * 4294967296;
        }

        result = (result & (~mask)) | value;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != result) {
            // Wrong write value
            BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]);
            ctx.valid = false;
            return;
        }

        trace("Updating future read values from write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function isValid(Context memory ctx) internal returns (bool) {
        if (ctx.writeAccesses.length != ctx.writeIdx) {
            // Excess reads
            ctx.valid = false;
        }
        return ctx.valid;
    }
}

library AVMMemoryContext32 {
    struct Context {
        uint256[] readAccesses;
        uint256[] writeAccesses;
        uint writeIdx;
        uint cachedRead;
        uint cachedReadValue;
        uint addressMask;
        uint addressMask32;
        uint addressMask256;
        bool valid;
    }

    event trace(string);
    event traceNum(uint);
    function initContext(uint256[] memory readAccesses, uint256[] memory writeAccesses, uint addressBits) internal returns (Context memory) {
        Context memory ctx;
        ctx.readAccesses = readAccesses;
        ctx.writeAccesses = writeAccesses;
        ctx.writeIdx = 0;
        ctx.addressMask = (2 ** addressBits) - 1;
        ctx.addressMask256 = ctx.addressMask ^ 31;
        ctx.addressMask32 = ctx.addressMask ^ 3;
        ctx.cachedRead = (uint) (-1);
        ctx.cachedReadValue = 0;
        ctx.valid = true;
        return ctx;
    }

    function read256(Context ctx, uint addr) internal returns (uint) {
        uint v;
        addr = addr & ctx.addressMask;

        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == (addr / 32)) {
                return ctx.readAccesses[i+1];
            }
        }

        ctx.valid = false;
        return 0;
    }

    function read32(Context ctx, uint addr) internal returns (uint32) {
        uint v = read256(ctx, addr);

        // Shift down to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            v = v / 4294967296;
        }

        return (uint32) (v);
    }

    function readByte(Context ctx, uint addr) internal returns (uint8) {
        uint32 v = read32(ctx, addr);

        for (uint j = (addr % 4); j < 3; j++) {
            v = v / 256;
        }

        return (uint8) (v);
    }

    function write256(Context ctx, uint addr, uint value) internal {
        addr = addr & ctx.addressMask;

        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            trace("Wrong write address");
            traceNum(addr);
            ctx.valid = false;
            return;
        }

        ctx.writeIdx++;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != value) {
            // Wrong write value
            trace("Wrong write value");
            traceNum(value);
            ctx.valid = false;
            return;
        }

        trace("Updating read values for write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function write32(Context ctx, uint addr, uint value) internal {
        trace("Write");
        if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) {
            // Insufficient writes
            trace("Insufficient Writes");
            ctx.valid = false;
            return;
        }

        trace("Reading write address");
        if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) {
            // Wrong write address
            trace("Wrong write address");
            traceNum(addr / 8);
            ctx.valid = false;
            return;
        }

        trace("Reading write prior value");
        uint result = ctx.writeAccesses[ctx.writeIdx++];
        uint mask = 4294967295;
        value = value & mask;

        // Shift up to chosen word
        for (uint j = ((addr / 4) % 8); j < 7; j++) {
            mask = mask * 4294967296;
            value = value * 4294967296;
        }

        result = (result & (~mask)) | value;

        trace("Reading write value");
        if (ctx.writeAccesses[ctx.writeIdx++] != result) {
            // Wrong write value
            trace("Wrong write value");
            traceNum(result);
            ctx.valid = false;
            return;
        }

        trace("Updating future read values from write");
        for (uint i = 0; i < ctx.readAccesses.length; i += 2) {
            if (ctx.readAccesses[i] == addr) {
                ctx.readAccesses[i+1] = value;
            }
        }
    }

    function isValid(Context memory ctx) internal returns (bool) {
        if (ctx.writeAccesses.length != ctx.writeIdx) {
            // Excess reads
            ctx.valid = false;
        }
        return ctx.valid;
    }
}


fix syntax errors

fix syntax errors

pragma solidity ^0.4.11;
import "./StandardToken.sol";
import "./PLCRVoting.sol";

/*
=======
 TO DO
=======

implement events
refactor & wrap check & transfer

*/

contract Registry {

    /*
     * Storage
     */

    //Registry storage
    StandardToken public token;
    PLCRVoting public voting;
    mapping(bytes32 => Publisher) public whitelist; //domainHash => Publisher struct
    mapping(bytes32 => Application) public appPool; //holds applications for both domain and parameter appPool
    mapping(bytes32 => Params) public paramSnapshots;
    mapping(uint => VoteInfo) public pollInfo; // holds information on individual polls
    mapping(address => mapping(uint => bool)) public voterInfo; // holds information on voters' token claims
    string domain;
    //Parameter storage
    mapping(bytes32 => uint) public Parameters;
    mapping(uint => bytes32) public idToHash;
    string parameter;
    uint value;

    struct Publisher {
        address owner;
        uint expTime;
        uint deposit;

        uint nextExpTime; //
        uint prevDeposit; // total withdrawable amount
        uint nextDeposit; //
        bool renewal;
    }

    struct Application {
        address owner;
        bool challenged;
        uint challengeTime; //End of challenge period
        address challenger;

        string domain;
        string parameter;
        uint value;
    }

    struct Params {
        // parameters concerning the whitelist and application pool
        uint minDeposit;
        uint challengeLen;
        uint registryLen;

        // parameters to be passed into the voting contract
        uint commitVoteLen;
        uint revealVoteLen;
        uint majority;

        // parameter representing the scale of how token rewards are distributed
        uint dispensationPct;
    }

    struct VoteInfo {
        // if the vote has been processed
        bool processed;
        // amount of leftover tokens available for winning party to claim
        // (a byproduct of needing to floor the distributed tokens to voters)
        uint256 remainder;
        address claimer;
    }

    // constant used to help represent doubles as ints
    uint256 constant private MULTIPLIER = 10 ** 18;

    /*
     * Constructor
     */
    /// @param _minDeposit      application & challenger deposit amounts
    /// @param _challengeLen    duration of the challenge period
    /// @param _registryLen     duration of a registration’s validity
    /// @param _commitVoteLen   duration of the commit period in token votes
    /// @param _revealVoteLen   duration of reveal period in token votes
    /// @param _dispensationPct percentage of forfeited deposit distributed to winning party; uint between 0 and 100
    /// @param _majority        percentage of votes that constitutes the majority; uint between 0 and 100

    function Registry(address _token,
        address _voting,
       uint _minDeposit,
       uint _challengeLen,
       uint _registryLen,
       uint _commitVoteLen,
       uint _revealVoteLen,
       uint _dispensationPct,
       uint _majority) {

       token = StandardToken(_token);
       voting = PLCRVoting(_voting);
       // initialize values
       Parameters[sha3("minDeposit")]        = _minDeposit;
       Parameters[sha3("challengeLen")]      = _challengeLen;
       Parameters[sha3("registryLen")]       = _registryLen;
       Parameters[sha3("commitVoteLen")]     = _commitVoteLen;
       Parameters[sha3("revealVoteLen")]     = _revealVoteLen;
       Parameters[sha3("dispensationPct")]   = _dispensationPct;
       Parameters[sha3("majority")]          = _majority;
    }

    // called by an applicant to add to application pool on success
    function apply(string _domain) public {
        bytes32 domainHash = sha3(_domain);
        // must be a new member of the whitelist
        require(whitelist[domainHash].owner == 0); //not on whitelist
        require(appPool[domainHash].owner == 0); //not in appPool
        // initialize with the current values of all parameters
        initializeSnapshot(domainHash);
        initApplication(domainHash, msg.sender);
        appPool[domainHash].domain = _domain;
    }

    // helper function to apply() and proposeUpdate()
    // obtain deposit from applicant and initialize challenge end time and owner
    function initApplication(bytes32 _hash, address _applicant) private {
        require(appPool[_hash].owner == 0); // prevent repeat applications

        // applicant must pay the current value of minDeposit
        uint deposit = paramSnapshots[_hash].minDeposit;
        require(token.transferFrom(_applicant, this, deposit));

        setAppAttr(_hash, _applicant);
    }

    //called by the owner of a domain on the whitelist
    //make necessary token transfers and initialize application for renewal in the appPool
    function renew (string _domain) {
        bytes32 domainHash = sha3(_domain);
        require(hasRenewal(domainHash) == false); //prevent duplicate renewals
        require(msg.sender == whitelist[domainHash].owner); // must be the owner of the domain
        uint minDeposit = get('minDeposit');
        uint lockedTok = whitelist[domainHash].deposit;
        uint unlockedTok = whitelist[domainHash].prevDeposit;
        uint extraNeeded;

        if (lockedTok + unlockedTok >= minDeposit)
        {//existing total num tokens is sufficient
            if (lockedTok >= minDeposit)
            {// have enough locked tok, only take from currently locked deposit
                whitelist[domainHash].deposit = lockedTok - minDeposit;
            }
            else //lockedTok < minDeposit
            {// not enough locked tok, take entire locked deposit and part of unlocked
                extraNeeded = minDeposit - lockedTok;
                //update num unlocked tokens
                whitelist[domainHash].prevDeposit = unlockedTok - extraNeeded;
                whitelist[domainHash].deposit = 0;  // ************?*********
            }
        }
        else
        { //existing total num tokens is not sufficient, must send in more tokens
            extraNeeded = minDeposit - (lockedTok + unlockedTok);
            require(token.transferFrom(msg.sender, this, extraNeeded));
            whitelist[domainHash].deposit = 0;
            whitelist[domainHash].prevDeposit = 0;
        }
        //apply
        initializeSnapshot(domainHash);
        setAppAttr(domainHash, msg.sender);
        whitelist[domainHash].renewal = true;
    }

    //called by the owner of a domain on the whitelist
    //withdraw any number of unlocked tokens
    function claimDeposit(string _domain, uint _amount) public {
        bytes32 domainHash = sha3(_domain);
        uint unlockedTok = whitelist[domainHash].prevDeposit;
        require(msg.sender == whitelist[domainHash].owner);
        require(unlockedTok >= _amount);
        require(token.transfer(msg.sender, _amount));
        whitelist[domainHash].prevDeposit = unlockedTok - _amount;
    }

    //called by the owner of a domain on the whitelist
    //renew the domain on the whitelist and allow additional renewals
    function activateRenewal(string _domain) public {
        bytes32 _hash = sha3(_domain);
        if (hasRenewal(_hash) && whitelist[_hash].expTime <= now)
        {
            whitelist[_hash].expTime = whitelist[_hash].nextExpTime;
            whitelist[_hash].prevDeposit += whitelist[_hash].deposit;
            whitelist[_hash].deposit = whitelist[_hash].nextDeposit;
            whitelist[_hash].renewal = false;
        }
    }

    // called by any adtoken holder to challenge an application to the whitelist
    // initialize vote to accept/reject a domain to the registry
    function challengeApplication(string _domain) public returns(uint) {
        bytes32 domainHash = sha3(_domain);
        challenge(domainHash, msg.sender);
        // start a vote
        uint pollID = callVote(_domain
        ,paramSnapshots[domainHash].majority
        ,paramSnapshots[domainHash].commitVoteLen
        ,paramSnapshots[domainHash].revealVoteLen);
        idToHash[pollID] = domainHash;
        return pollID;
    }

    // helper function to challengeApplication() and challengeProposal()
    function challenge(bytes32 _hash, address _challenger) private {
        // check that registry can take sufficient amount of tokens from the challenger
        uint deposit = paramSnapshots[_hash].minDeposit;
        require(token.allowance(_challenger, this) >= deposit);
        token.transferFrom(_challenger, this, deposit);

        // prevent someone from challenging an unintialized application, rechallenging,
        // or challenging after the challenge period has ended
        require(appPool[_hash].owner != 0);
        require(appPool[_hash].challenged == false);
        require(appPool[_hash].challengeTime > now);

        // update the application's status
        appPool[_hash].challenged = true;
        appPool[_hash].challenger = _challenger;
    }

    // helper function to the challenge() function. Initializes a vote through the voting contract
    // returns a poll id
    function callVote(string _proposalString, uint _majority, uint _commitVoteLen,
        uint _revealVoteLen) private returns (uint) {
        // event that vote has started
        uint pollID = voting.startPoll( _proposalString, _majority, _commitVoteLen,  _revealVoteLen);
        return pollID;
    }

    // a one-time function for each completed vote
    // if domain won: domain is moved to the whitelist and applicant is rewarded tokens, return true
    // if domain lost: challenger is rewarded tokens, return false
    function processResult(uint _pollID) returns(bool)
    {
        bytes32 domainHash = idToHash[_pollID];
        require(isDomainApp(domainHash));  // processing parameter hash this way is unintended behavior
        require(pollInfo[_pollID].processed == false);
        // ensures the result cannot be processed again
        pollInfo[_pollID].processed = true;

        if (voting.isPassed(_pollID)) {
            // add to registry
            add(domainHash, appPool[domainHash].owner);
            pollInfo[_pollID].claimer = appPool[domainHash].owner;
            // give tokens to applicant based on dist and total tokens
            giveWinnerReward(domainHash, appPool[domainHash].owner);
            // uninitialize application
            delete appPool[domainHash].owner;
            return true;
        }
        else {
            pollInfo[_pollID].claimer = appPool[domainHash].challenger;
            giveWinnerReward(domainHash, appPool[domainHash].challenger);
            token.transfer(appPool[domainHash].challenger, paramSnapshots[domainHash].minDeposit);
            delete appPool[domainHash].owner;
            return false;
        }
    }

    // helper function to processResult()
    // reward a portion of minDeposit to _address
    // reward extra token to _address if dispensationPct does not divide minDeposit evenly
    function giveWinnerReward(bytes32 _hash, address _address) private {
        uint256 minDeposit = paramSnapshots[_hash].minDeposit;
        uint256 dispensationPct = paramSnapshots[_hash].dispensationPct;
        uint256 rewardTokens = minDeposit * (dispensationPct) / 100;
        if ((minDeposit * dispensationPct) % 100 != 0) {
            rewardTokens++;
        }
        require(token.transfer(_address, rewardTokens));
    }

    // called by each voter to claim their reward for each completed vote
    function claimReward(uint _pollID, uint _salt) {
        // ensure voter has not already claimed tokens
        require(voterInfo[msg.sender][_pollID] == false);
        uint reward = giveTokens(_pollID, _salt, msg.sender);
        // ensures a voter cannot claim tokens again
        require(token.transfer(msg.sender, reward));
        voterInfo[msg.sender][_pollID] = true;
    }

    // number of tokens person used to vote / total number of tokens for winning side
    // scale using distribution number, give the tokens
    function giveTokens(uint _pollID, uint _salt, address _voter) private returns(uint) {
        bytes32 hash = idToHash[_pollID];
        uint256 minDeposit = paramSnapshots[hash].minDeposit;
        uint256 dispensationPct = paramSnapshots[hash].dispensationPct;
        uint256 totalTokens = voting.getTotalNumberOfTokensForWinningOption(_pollID);
        uint256 voterTokens = voting.getNumPassingTokens(_pollID, _salt, _voter);

        uint256 rewardTokens = minDeposit * (100 - dispensationPct)*MULTIPLIER / 100;
        //what happens if expression does not divide evenly
        uint256 numerator = voterTokens * rewardTokens;
        uint256 denominator = totalTokens * MULTIPLIER;
        uint256 remainder = numerator % denominator;

        // save remainder tokens in the form of decimal numbers with 18 places represented
        // as a uint256
        pollInfo[_pollID].remainder += remainder;

        return numerator / denominator;
    }

    function claimExtraReward(uint _pollID) {
        uint256 totalTokens = voting.getTotalNumberOfTokensForWinningOption(_pollID);
        uint256 reward = pollInfo[_pollID].remainder / (MULTIPLIER);
        reward = reward / totalTokens
        pollInfo[_pollID].remainder = pollInfo[_pollID].remainder - reward * MULTIPLIER;
        token.transfer(pollInfo[_pollID].claimer, reward);
    }

    // called to move an applying domain to the whitelist
    // iff the domain's challenge period has passed without a challenge
    function moveToRegistry(string _domain) public {
        bytes32 domainHash = sha3(_domain);
        require(appPool[domainHash].challengeTime < now);
        require(appPool[domainHash].challenged == false);
        // prevents moving a domain to the registry without ever applying
        require(appPool[domainHash].owner != 0);
        // prevent applicant from moving to registry multiple times
        add(domainHash, appPool[domainHash].owner);
        delete appPool[domainHash].owner; //remove from appPool
    }

    // ISSUE WITH OVERLAP

    // private function to add a domain name to the whitelist
    function add(bytes32 _domainHash, address _owner) private {
        uint expiration = paramSnapshots[_domainHash].registryLen;
        if (whitelist[_domainHash].renewal == true)
        {
            whitelist[_domainHash].nextExpTime = whitelist[_domainHash].expTime + expiration;
            whitelist[_domainHash].nextDeposit = paramSnapshots[_domainHash].minDeposit;
        }
        else
        {
            whitelist[_domainHash].expTime = now + expiration;
            whitelist[_domainHash].deposit = paramSnapshots[_domainHash].minDeposit;
        }
        whitelist[_domainHash].owner = _owner;
    }

    /*
     * Helper Functions
     */

    // STATIC

    // returns true if a renewal has been initialized
    function hasRenewal(bytes32 _hash) private constant returns (bool) {
        return whitelist[_hash].renewal;
    }

    // returns true if Application is for domain and not parameter
    function isDomainApp(bytes32 _hash) private constant returns(bool){
        return bytes(appPool[_hash].parameter).length == 0;  // checks if param string is initialized
    }

    // returns true if a domain name is in the whitelist and unexpired
    // provided for the user to verify the status of their domain
    function isInRegistry(string _domain) public constant returns (bool) {
        bytes32 domainHash = sha3(_domain);
        return whitelist[domainHash].expTime > now;
    }

    // DYNAMIC

    // Initialize snapshot of parameters for each application
    function initializeSnapshot(bytes32 _hash) private {
        initializeSnapshotParam(_hash);  // maybe put the two together
        paramSnapshots[_hash].registryLen = get("registryLen");
    }

    //set the challenge end time and the owner of an application
    function setAppAttr(bytes32 _hash, address _applicant) private {
        appPool[_hash].challengeTime = now + paramSnapshots[_hash].challengeLen;
        appPool[_hash].owner = _applicant;
    }

/*****************************************************************************/

    //called by a user who wishes to change a parameter
    //initializes a proposal to change a parameter
    function proposeUpdate(string _parameter, uint _value) public {
        //require(_parameter != "");
        bytes32 parameterHash = sha3(_parameter, _value);
        // initialize application with a with the current values of all parameters
        initializeSnapshotParam(parameterHash);
        initApplication(parameterHash, msg.sender);
        appPool[parameterHash].parameter = _parameter;
        appPool[parameterHash].value = _value;
    }

    //called by user who wishes to reject a proposal
    //initializes a vote to accept/reject the param change proposal
    function challengeProposal(string _parameter, uint _value) public {
        bytes32 parameterHash = sha3(_parameter, _value);
        challenge(parameterHash, msg.sender);
        // start a vote
        uint pollID = callVote(_parameter
        ,paramSnapshots[parameterHash].majority
        ,paramSnapshots[parameterHash].commitVoteLen
        ,paramSnapshots[parameterHash].revealVoteLen);
        idToHash[pollID] = parameterHash;
    }

    // called to change parameter
    // iff the proposal's challenge period has passed without a challenge
    function setParams(string _parameter, uint _value) public {
        bytes32 parameterHash = sha3(_parameter, _value);
        require(appPool[parameterHash].challengeTime < now);
        require(appPool[parameterHash].challenged == false);
        // prevents moving a domain to the registry without ever applying
        require(appPool[parameterHash].owner != 0);
        // prevent applicant from moving to registry multiple times
        Parameters[sha3(_parameter)] = _value;
        delete appPool[parameterHash].owner;
    }

    // a one-time function for each completed vote
    // if proposal won: new parameter value is set, and applicant is rewarded tokens, return true
    // if prospsal lost: challenger is rewarded tokens, return false
    function processProposal(uint _pollID) returns(bool)
    {
        require(pollInfo[_pollID].processed == false);
        bytes32 parameterHash = idToHash[_pollID];
        parameter = appPool[parameterHash].parameter;
        value = appPool[parameterHash].value;
        delete appPool[parameterHash].owner;

        if (voting.isPassed(_pollID)) {
            pollInfo[_pollID].claimer = appPool[parameterHash].owner;
            // setting the value of parameter
            Parameters[sha3(parameter)] = value;
            // give tokens to applicant based on dist and total tokens IMPLEMENT
            giveWinnerReward(parameterHash, appPool[parameterHash].owner);
            token.transfer(appPool[parameterHash].owner, paramSnapshots[parameterHash].minDeposit);
            return true;
        }
        else {
            pollInfo[_pollID].claimer = appPool[parameterHash].challenger;
            // give tokens to challenger based on dist and total tokens
            giveWinnerReward(parameterHash, appPool[parameterHash].challenger);
            token.transfer(appPool[parameterHash].challenger, paramSnapshots[parameterHash].minDeposit);
            return false;
        }
        // ensures the result cannot be processed again
        pollInfo[_pollID].processed = true;
    }

     // private function to initialize a snapshot of parameters for each proposal
     function initializeSnapshotParam(bytes32 _hash) private {
        paramSnapshots[_hash].minDeposit = get("minDeposit");
        paramSnapshots[_hash].challengeLen = get("challengeLen");
        paramSnapshots[_hash].commitVoteLen = get("commitVoteLen");
        paramSnapshots[_hash].revealVoteLen = get("revealVoteLen");
        paramSnapshots[_hash].majority = get("majority");
        paramSnapshots[_hash].dispensationPct = get("dispensationPct");
    }

    // interface for retrieving config parameter from hashmapping
    /// @param _keyword key for hashmap (only useful when keyword matches variable name)
    function get(string _keyword) public constant returns (uint) {
       return Parameters[sha3(_keyword)];
    }

/*****************************************************************************/

    // Helper Functions
     // FOR TESTING
    function toHash(string _domain) returns (bytes32){
        return sha3(_domain);
    }
    function toParameterHash(string _parameter, uint _value) returns (bytes32){
        return sha3(_parameter, _value);
    }
    function getCurrentTime() returns (uint){
        return now;
    }

}

pragma solidity ^0.4.11;
import "./StandardToken.sol";
import "./PLCRVoting.sol";

/*
=======
 TO DO
=======

implement events
refactor & wrap check & transfer

*/

contract Registry {

    /*
     * Storage
     */

    //Registry storage
    StandardToken public token;
    PLCRVoting public voting;
    mapping(bytes32 => Publisher) public whitelist; //domainHash => Publisher struct
    mapping(bytes32 => Application) public appPool; //holds applications for both domain and parameter appPool
    mapping(bytes32 => Params) public paramSnapshots;
    mapping(uint => VoteInfo) public pollInfo; // holds information on individual polls
    mapping(address => mapping(uint => bool)) public voterInfo; // holds information on voters' token claims
    string domain;
    //Parameter storage
    mapping(bytes32 => uint) public Parameters;
    mapping(uint => bytes32) public idToHash;
    string parameter;
    uint value;

    struct Publisher {
        address owner;
        uint expTime;
        uint deposit;

        uint nextExpTime; //
        uint prevDeposit; // total withdrawable amount
        uint nextDeposit; //
        bool renewal;
    }

    struct Application {
        address owner;
        bool challenged;
        uint challengeTime; //End of challenge period
        address challenger;

        string domain;
        string parameter;
        uint value;
    }

    struct Params {
        // parameters concerning the whitelist and application pool
        uint minDeposit;
        uint challengeLen;
        uint registryLen;

        // parameters to be passed into the voting contract
        uint commitVoteLen;
        uint revealVoteLen;
        uint majority;

        // parameter representing the scale of how token rewards are distributed
        uint dispensationPct;
    }

    struct VoteInfo {
        // if the vote has been processed
        bool processed;
        // amount of leftover tokens available for winning party to claim
        // (a byproduct of needing to floor the distributed tokens to voters)
        uint256 remainder;
        address claimer;
    }

    // constant used to help represent doubles as ints
    uint256 constant private MULTIPLIER = 10 ** 18;

    /*
     * Constructor
     */
    /// @param _minDeposit      application & challenger deposit amounts
    /// @param _challengeLen    duration of the challenge period
    /// @param _registryLen     duration of a registration’s validity
    /// @param _commitVoteLen   duration of the commit period in token votes
    /// @param _revealVoteLen   duration of reveal period in token votes
    /// @param _dispensationPct percentage of forfeited deposit distributed to winning party; uint between 0 and 100
    /// @param _majority        percentage of votes that constitutes the majority; uint between 0 and 100

    function Registry(address _token,
        address _voting,
       uint _minDeposit,
       uint _challengeLen,
       uint _registryLen,
       uint _commitVoteLen,
       uint _revealVoteLen,
       uint _dispensationPct,
       uint _majority) {

       token = StandardToken(_token);
       voting = PLCRVoting(_voting);
       // initialize values
       Parameters[sha3("minDeposit")]        = _minDeposit;
       Parameters[sha3("challengeLen")]      = _challengeLen;
       Parameters[sha3("registryLen")]       = _registryLen;
       Parameters[sha3("commitVoteLen")]     = _commitVoteLen;
       Parameters[sha3("revealVoteLen")]     = _revealVoteLen;
       Parameters[sha3("dispensationPct")]   = _dispensationPct;
       Parameters[sha3("majority")]          = _majority;
    }

    // called by an applicant to add to application pool on success
    function apply(string _domain) public {
        bytes32 domainHash = sha3(_domain);
        // must be a new member of the whitelist
        require(whitelist[domainHash].owner == 0); //not on whitelist
        require(appPool[domainHash].owner == 0); //not in appPool
        // initialize with the current values of all parameters
        initializeSnapshot(domainHash);
        initApplication(domainHash, msg.sender);
        appPool[domainHash].domain = _domain;
    }

    // helper function to apply() and proposeUpdate()
    // obtain deposit from applicant and initialize challenge end time and owner
    function initApplication(bytes32 _hash, address _applicant) private {
        require(appPool[_hash].owner == 0); // prevent repeat applications

        // applicant must pay the current value of minDeposit
        uint deposit = paramSnapshots[_hash].minDeposit;
        require(token.transferFrom(_applicant, this, deposit));

        setAppAttr(_hash, _applicant);
    }

    //called by the owner of a domain on the whitelist
    //make necessary token transfers and initialize application for renewal in the appPool
    function renew (string _domain) {
        bytes32 domainHash = sha3(_domain);
        require(hasRenewal(domainHash) == false); //prevent duplicate renewals
        require(msg.sender == whitelist[domainHash].owner); // must be the owner of the domain
        uint minDeposit = get('minDeposit');
        uint lockedTok = whitelist[domainHash].deposit;
        uint unlockedTok = whitelist[domainHash].prevDeposit;
        uint extraNeeded;

        if (lockedTok + unlockedTok >= minDeposit)
        {//existing total num tokens is sufficient
            if (lockedTok >= minDeposit)
            {// have enough locked tok, only take from currently locked deposit
                whitelist[domainHash].deposit = lockedTok - minDeposit;
            }
            else //lockedTok < minDeposit
            {// not enough locked tok, take entire locked deposit and part of unlocked
                extraNeeded = minDeposit - lockedTok;
                //update num unlocked tokens
                whitelist[domainHash].prevDeposit = unlockedTok - extraNeeded;
                whitelist[domainHash].deposit = 0;  // ************?*********
            }
        }
        else
        { //existing total num tokens is not sufficient, must send in more tokens
            extraNeeded = minDeposit - (lockedTok + unlockedTok);
            require(token.transferFrom(msg.sender, this, extraNeeded));
            whitelist[domainHash].deposit = 0;
            whitelist[domainHash].prevDeposit = 0;
        }
        //apply
        initializeSnapshot(domainHash);
        setAppAttr(domainHash, msg.sender);
        whitelist[domainHash].renewal = true;
    }

    //called by the owner of a domain on the whitelist
    //withdraw any number of unlocked tokens
    function claimDeposit(string _domain, uint _amount) public {
        bytes32 domainHash = sha3(_domain);
        uint unlockedTok = whitelist[domainHash].prevDeposit;
        require(msg.sender == whitelist[domainHash].owner);
        require(unlockedTok >= _amount);
        require(token.transfer(msg.sender, _amount));
        whitelist[domainHash].prevDeposit = unlockedTok - _amount;
    }

    //called by the owner of a domain on the whitelist
    //renew the domain on the whitelist and allow additional renewals
    function activateRenewal(string _domain) public {
        bytes32 _hash = sha3(_domain);
        if (hasRenewal(_hash) && whitelist[_hash].expTime <= now)
        {
            whitelist[_hash].expTime = whitelist[_hash].nextExpTime;
            whitelist[_hash].prevDeposit += whitelist[_hash].deposit;
            whitelist[_hash].deposit = whitelist[_hash].nextDeposit;
            whitelist[_hash].renewal = false;
        }
    }

    // called by any adtoken holder to challenge an application to the whitelist
    // initialize vote to accept/reject a domain to the registry
    function challengeApplication(string _domain) public returns(uint) {
        bytes32 domainHash = sha3(_domain);
        challenge(domainHash, msg.sender);
        // start a vote
        uint pollID = callVote(_domain
        ,paramSnapshots[domainHash].majority
        ,paramSnapshots[domainHash].commitVoteLen
        ,paramSnapshots[domainHash].revealVoteLen);
        idToHash[pollID] = domainHash;
        return pollID;
    }

    // helper function to challengeApplication() and challengeProposal()
    function challenge(bytes32 _hash, address _challenger) private {
        // check that registry can take sufficient amount of tokens from the challenger
        uint deposit = paramSnapshots[_hash].minDeposit;
        require(token.allowance(_challenger, this) >= deposit);
        token.transferFrom(_challenger, this, deposit);

        // prevent someone from challenging an unintialized application, rechallenging,
        // or challenging after the challenge period has ended
        require(appPool[_hash].owner != 0);
        require(appPool[_hash].challenged == false);
        require(appPool[_hash].challengeTime > now);

        // update the application's status
        appPool[_hash].challenged = true;
        appPool[_hash].challenger = _challenger;
    }

    // helper function to the challenge() function. Initializes a vote through the voting contract
    // returns a poll id
    function callVote(string _proposalString, uint _majority, uint _commitVoteLen,
        uint _revealVoteLen) private returns (uint) {
        // event that vote has started
        uint pollID = voting.startPoll( _proposalString, _majority, _commitVoteLen,  _revealVoteLen);
        return pollID;
    }

    // a one-time function for each completed vote
    // if domain won: domain is moved to the whitelist and applicant is rewarded tokens, return true
    // if domain lost: challenger is rewarded tokens, return false
    function processResult(uint _pollID) returns(bool)
    {
        bytes32 domainHash = idToHash[_pollID];
        require(isDomainApp(domainHash));  // processing parameter hash this way is unintended behavior
        require(pollInfo[_pollID].processed == false);
        // ensures the result cannot be processed again
        pollInfo[_pollID].processed = true;

        if (voting.isPassed(_pollID)) {
            // add to registry
            add(domainHash, appPool[domainHash].owner);
            pollInfo[_pollID].claimer = appPool[domainHash].owner;
            // give tokens to applicant based on dist and total tokens
            giveWinnerReward(domainHash, appPool[domainHash].owner);
            // uninitialize application
            delete appPool[domainHash].owner;
            return true;
        }
        else {
            pollInfo[_pollID].claimer = appPool[domainHash].challenger;
            giveWinnerReward(domainHash, appPool[domainHash].challenger);
            token.transfer(appPool[domainHash].challenger, paramSnapshots[domainHash].minDeposit);
            delete appPool[domainHash].owner;
            return false;
        }
    }

    // helper function to processResult()
    // reward a portion of minDeposit to _address
    // reward extra token to _address if dispensationPct does not divide minDeposit evenly
    function giveWinnerReward(bytes32 _hash, address _address) private {
        uint256 minDeposit = paramSnapshots[_hash].minDeposit;
        uint256 dispensationPct = paramSnapshots[_hash].dispensationPct;
        uint256 rewardTokens = minDeposit * (dispensationPct) / 100;
        if ((minDeposit * dispensationPct) % 100 != 0) {
            rewardTokens++;
        }
        require(token.transfer(_address, rewardTokens));
    }

    // called by each voter to claim their reward for each completed vote
    function claimReward(uint _pollID, uint _salt) {
        // ensure voter has not already claimed tokens
        require(voterInfo[msg.sender][_pollID] == false);
        uint reward = giveTokens(_pollID, _salt, msg.sender);
        // ensures a voter cannot claim tokens again
        require(token.transfer(msg.sender, reward));
        voterInfo[msg.sender][_pollID] = true;
    }

    // number of tokens person used to vote / total number of tokens for winning side
    // scale using distribution number, give the tokens
    function giveTokens(uint _pollID, uint _salt, address _voter) private returns(uint) {
        bytes32 hash = idToHash[_pollID];
        uint256 minDeposit = paramSnapshots[hash].minDeposit;
        uint256 dispensationPct = paramSnapshots[hash].dispensationPct;
        uint256 totalTokens = voting.getTotalNumberOfTokensForWinningOption(_pollID);
        uint256 voterTokens = voting.getNumPassingTokens(_pollID, _salt, _voter);

        uint256 rewardTokens = minDeposit * (100 - dispensationPct) / 100;
        uint256 numerator = voterTokens * rewardTokens * MULTIPLIER;
        uint256 denominator = totalTokens * MULTIPLIER;
        uint256 remainder = numerator % denominator;

        // save remainder tokens in the form of decimal numbers with 18 places represented
        // as a uint256
        pollInfo[_pollID].remainder += remainder;

        return numerator / denominator;
    }

    // called to move an applying domain to the whitelist
    // iff the domain's challenge period has passed without a challenge
    function moveToRegistry(string _domain) public {
        bytes32 domainHash = sha3(_domain);
        require(appPool[domainHash].challengeTime < now);
        require(appPool[domainHash].challenged == false);
        // prevents moving a domain to the registry without ever applying
        require(appPool[domainHash].owner != 0);
        // prevent applicant from moving to registry multiple times
        add(domainHash, appPool[domainHash].owner);
        delete appPool[domainHash].owner; //remove from appPool
    }

    // ISSUE WITH OVERLAP

    // private function to add a domain name to the whitelist
    function add(bytes32 _domainHash, address _owner) private {
        uint expiration = paramSnapshots[_domainHash].registryLen;
        if (whitelist[_domainHash].renewal == true)
        {
            whitelist[_domainHash].nextExpTime = whitelist[_domainHash].expTime + expiration;
            whitelist[_domainHash].nextDeposit = paramSnapshots[_domainHash].minDeposit;
        }
        else
        {
            whitelist[_domainHash].expTime = now + expiration;
            whitelist[_domainHash].deposit = paramSnapshots[_domainHash].minDeposit;
        }
        whitelist[_domainHash].owner = _owner;
    }

    /*
     * Helper Functions
     */

    // STATIC

    // returns true if a renewal has been initialized
    function hasRenewal(bytes32 _hash) private constant returns (bool) {
        return whitelist[_hash].renewal;
    }

    // returns true if Application is for domain and not parameter
    function isDomainApp(bytes32 _hash) private constant returns(bool){
        return bytes(appPool[_hash].parameter).length == 0;  // checks if param string is initialized
    }

    // returns true if a domain name is in the whitelist and unexpired
    // provided for the user to verify the status of their domain
    function isInRegistry(string _domain) public constant returns (bool) {
        bytes32 domainHash = sha3(_domain);
        return whitelist[domainHash].expTime > now;
    }

    // DYNAMIC

    // Initialize snapshot of parameters for each application
    function initializeSnapshot(bytes32 _hash) private {
        initializeSnapshotParam(_hash);  // maybe put the two together
        paramSnapshots[_hash].registryLen = get("registryLen");
    }

    //set the challenge end time and the owner of an application
    function setAppAttr(bytes32 _hash, address _applicant) private {
        appPool[_hash].challengeTime = now + paramSnapshots[_hash].challengeLen;
        appPool[_hash].owner = _applicant;
    }

/*****************************************************************************/

    //called by a user who wishes to change a parameter
    //initializes a proposal to change a parameter
    function proposeUpdate(string _parameter, uint _value) public {
        //require(_parameter != "");
        bytes32 parameterHash = sha3(_parameter, _value);
        // initialize application with a with the current values of all parameters
        initializeSnapshotParam(parameterHash);
        initApplication(parameterHash, msg.sender);
        appPool[parameterHash].parameter = _parameter;
        appPool[parameterHash].value = _value;
    }

    //called by user who wishes to reject a proposal
    //initializes a vote to accept/reject the param change proposal
    function challengeProposal(string _parameter, uint _value) public {
        bytes32 parameterHash = sha3(_parameter, _value);
        challenge(parameterHash, msg.sender);
        // start a vote
        uint pollID = callVote(_parameter
        ,paramSnapshots[parameterHash].majority
        ,paramSnapshots[parameterHash].commitVoteLen
        ,paramSnapshots[parameterHash].revealVoteLen);
        idToHash[pollID] = parameterHash;
    }

    // called to change parameter
    // iff the proposal's challenge period has passed without a challenge
    function setParams(string _parameter, uint _value) public {
        bytes32 parameterHash = sha3(_parameter, _value);
        require(appPool[parameterHash].challengeTime < now);
        require(appPool[parameterHash].challenged == false);
        // prevents moving a domain to the registry without ever applying
        require(appPool[parameterHash].owner != 0);
        // prevent applicant from moving to registry multiple times
        Parameters[sha3(_parameter)] = _value;
        delete appPool[parameterHash].owner;
    }

    // a one-time function for each completed vote
    // if proposal won: new parameter value is set, and applicant is rewarded tokens, return true
    // if prospsal lost: challenger is rewarded tokens, return false
    function processProposal(uint _pollID) returns(bool)
    {
        require(pollInfo[_pollID].processed == false);
        bytes32 parameterHash = idToHash[_pollID];
        parameter = appPool[parameterHash].parameter;
        value = appPool[parameterHash].value;
        delete appPool[parameterHash].owner;

        if (voting.isPassed(_pollID)) {
            pollInfo[_pollID].claimer = appPool[parameterHash].owner;
            // setting the value of parameter
            Parameters[sha3(parameter)] = value;
            // give tokens to applicant based on dist and total tokens IMPLEMENT
            giveWinnerReward(parameterHash, appPool[parameterHash].owner);
            token.transfer(appPool[parameterHash].owner, paramSnapshots[parameterHash].minDeposit);
            return true;
        }
        else {
            pollInfo[_pollID].claimer = appPool[parameterHash].challenger;
            // give tokens to challenger based on dist and total tokens
            giveWinnerReward(parameterHash, appPool[parameterHash].challenger);
            token.transfer(appPool[parameterHash].challenger, paramSnapshots[parameterHash].minDeposit);
            return false;
        }
        // ensures the result cannot be processed again
        pollInfo[_pollID].processed = true;
    }

     // private function to initialize a snapshot of parameters for each proposal
     function initializeSnapshotParam(bytes32 _hash) private {
        paramSnapshots[_hash].minDeposit = get("minDeposit");
        paramSnapshots[_hash].challengeLen = get("challengeLen");
        paramSnapshots[_hash].commitVoteLen = get("commitVoteLen");
        paramSnapshots[_hash].revealVoteLen = get("revealVoteLen");
        paramSnapshots[_hash].majority = get("majority");
        paramSnapshots[_hash].dispensationPct = get("dispensationPct");
    }

    // interface for retrieving config parameter from hashmapping
    /// @param _keyword key for hashmap (only useful when keyword matches variable name)
    function get(string _keyword) public constant returns (uint) {
       return Parameters[sha3(_keyword)];
    }

/*****************************************************************************/

    // Helper Functions
     // FOR TESTING
    function toHash(string _domain) returns (bytes32){
        return sha3(_domain);
    }
    function toParameterHash(string _parameter, uint _value) returns (bytes32){
        return sha3(_parameter, _value);
    }
    function getCurrentTime() returns (uint){
        return now;
    }

}


contract

contract

pragma solidity ^0.4.8;

import "./SafeMath.sol";

contract DetherTx is SafeMath {
  struct Details {
      // if possible check if it is an uniq username
      string username;
      uint price;
      uint balance;
      uint volumeTrade;
      uint nbTrade;
      string localizationGpsX;
      string localizationGpsY;
      uint commentIpfsId;
  }

  address[] public listAdressesUsers;

  mapping(address => Details) public users;

  event Transfer (address indexed _from, address indexed _to, uint256 _value);

  function DetherTx() {
  }

  function sendCoin (address receiver, uint amount) returns(bool sufficient) {
    if (users[msg.sender].balance < amount) return false;
    users[msg.sender].balance = safeSub(users[msg.sender].balance, amount);
    users[msg.sender].volumeTrade = safeAdd(users[msg.sender].volumeTrade, amount);
    users[receiver].volumeTrade = safeAdd(users[receiver].volumeTrade, amount);
    ++users[receiver].nbTrade;
    ++users[msg.sender].nbTrade;
    uint amountWithoutFees = safeSub(amount, (amount * 1/100));
    users[receiver].balance = safeAdd(users[receiver].balance, amountWithoutFees);
    Transfer(msg.sender, receiver, amountWithoutFees);

    return true;
  }

  function getBalance () constant returns(uint) {
    return users[msg.sender].balance;
  }

  function getVolume () constant returns(uint) {
    return users[msg.sender].volumeTrade;
  }

  function getNbTrade () constant returns(uint) {
    return users[msg.sender].nbTrade;
  }

  function deposit () payable returns (uint) {
    return  users[msg.sender].balance += msg.value ;
    //return SafeMath.safeAdd(users[msg.sender].balance,msg.value );
  }

  /// add and change the wallet of a passager
  function addAccount
  (
    string _username,
    uint _price,
    string _localizationGpsX,
    string _localizationGpsY,
    uint _commentIpfsId
  ) returns (
    string,
    uint,
    string,
    string,
    uint
  ) {
     Details details = users[msg.sender];
     details.username = _username;
     details.price = _price;
     details.balance = 0;
     details.volumeTrade = 0;
     details.nbTrade = 0;
     details.localizationGpsX = _localizationGpsX;
     details.localizationGpsY = _localizationGpsY;
     details.commentIpfsId = _commentIpfsId;

     ++listAdressesUsers.length;
     listAdressesUsers[listAdressesUsers.length-1] = msg.sender;

     return (
       _username,
       _price
       _localizationGpsX,
       _localizationGpsY,
       _commentIpfsId
     );
  }

  function withdraw (uint _amount) {
    if (users[msg.sender].balance < _amount) throw;
    // It is important to set this to zero because the recipient
    // can call this function again as part of the receiving call
    // before `send` returns.

    //users[msg.sender].balance -= _amount;
    users[msg.sender].balance = safeSub(users[msg.sender].balance,_amount);

    var amount = _amount;

    if(!msg.sender.send(amount)) throw;
  }

  function getAddressesAccounts () constant returns (address[]) {
    return listAdressesUsers;
  }

  function getAccount (address _user) constant returns (
      uint,
      uint,
      uint,
      uint,
      string,
      string,
      uint
    ) {
    return (
      users[_user].price,
      users[_user].balance,
      users[_user].volumeTrade,
      users[_user].nbTrade,
      users[_user].localizationGpsX,
      users[_user].localizationGpsY,
      users[_user].commentIpfsId
    );
  }

  // fallback
  function () payable {}
}

pragma solidity ^0.4.8;

import "./SafeMath.sol";

contract DetherTx {
  struct Details {
      // if possible check if it is an uniq username
      string username;
      uint price;
      uint balance;
      uint volumeTrade;
      uint nbTrade;
      uint localizationGpsX;
      uint localizationGpsY;
      uint commentIpfsId;
  }

  address[] public listAdressesUsers;

  mapping(address => Details) public users;

	event Transfer (address indexed _from, address indexed _to, uint256 _value);

	function DetherTx() {
	}

	function sendCoin (address receiver, uint amount) returns(bool sufficient) {
		if (users[msg.sender].balance < amount) return false;
    users[msg.sender].balance = SafeMath.safeSub(users[msg.sender].balance, amount);
    users[msg.sender].volumeTrade = SafeMath.safeAdd(users[msg.sender].volumeTrade, amount);
    users[receiver].volumeTrade = SafeMath.safeAdd(users[receiver].volumeTrade, amount);
    ++users[receiver].nbTrade;
    ++users[msg.sender].nbTrade;
    uint amountWithoutFees = SafeMath.safeSub(amount, (amount * 1/100));
    users[receiver].balance = SafeMath.safeAdd(users[receiver].balance, amountWithoutFees);
    Transfer(msg.sender, receiver, amountWithoutFees);

		return true;
	}

	function getBalance () constant returns(uint) {
		return users[msg.sender].balance;
	}

  function getVolume () constant returns(uint) {
    return users[msg.sender].volumeTrade;
  }

  function getNbTrade () constant returns(uint) {
    return users[msg.sender].nbTrade;
  }

  function deposit () payable returns (uint) {
    return  users[msg.sender].balance += msg.value ;
    //return SafeMath.safeAdd(users[msg.sender].balance,msg.value );
  }

  /// add and change the wallet of a passager
  function addAccount
  (
    string _username,
    uint _price,
    uint _localizationGpsX,
    uint _localizationGpsY,
    uint _commentIpfsId
  ) returns (
    string,
    uint,
    uint,
    uint,
    uint
  ) {
     Details details = users[msg.sender];
     details.username = _username;
     details.balance = 0;
     details.volumeTrade = 0;
     details.nbTrade = 0;
     details.localizationGpsX = _localizationGpsX;
     details.localizationGpsY = _localizationGpsY;
     details.commentIpfsId = _commentIpfsId;

     ++listAdressesUsers.length;
     listAdressesUsers[listAdressesUsers.length-1] = msg.sender;

     return (
       _username,
       _price
       _localizationGpsX,
       _localizationGpsY,
       _commentIpfsId
     );
  }

  function withdraw (uint _amount) {
    if (users[msg.sender].balance < _amount) throw;
    // It is important to set this to zero because the recipient
    // can call this function again as part of the receiving call
    // before `send` returns.

    //users[msg.sender].balance -= _amount;
    users[msg.sender].balance = SafeMath.safeSub(users[msg.sender].balance,_amount);

    var amount = _amount;

    if(!msg.sender.send(amount)) throw;
  }

  function getAddressesAccounts () constant returns (address[]) {
    return listAdressesUsers;
  }

  function getAccount (address _user) constant returns (
      string,
      uint,
      uint,
      uint,
      uint,
      uint,
      uint
    ) {
    return (
      users[_user].username,
      users[_user].balance,
      users[_user].volumeTrade,
      users[_user].nbTrade,
      users[_user].localizationGpsX,
      users[_user].localizationGpsY,
      users[_user].commentIpfsId
    );
  }

  // fallback
  function () payable {}
}


Remove excessive condition from SafeMath.safeAdd()

There is no situation when `c>=a` will be `true` while `c>=b` will be `false`.

pragma solidity ^0.4.8;

/**
 * Math operations with safety checks
 */
contract SafeMath {
  function safeMul(uint a, uint b) internal returns (uint) {
    uint c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function safeDiv(uint a, uint b) internal returns (uint) {
    assert(b > 0);
    uint c = a / b;
    assert(a == b * c + a % b);
    return c;
  }

  function safeSub(uint a, uint b) internal returns (uint) {
    assert(b <= a);
    return a - b;
  }

  function safeAdd(uint a, uint b) internal returns (uint) {
    uint c = a + b;
    assert(c >= a);
    return c;
  }

  function max64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a >= b ? a : b;
  }

  function min64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a < b ? a : b;
  }

  function max256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a >= b ? a : b;
  }

  function min256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a < b ? a : b;
  }

  function assert(bool assertion) internal {
    if (!assertion) {
      throw;
    }
  }
}

pragma solidity ^0.4.8;

/**
 * Math operations with safety checks
 */
contract SafeMath {
  function safeMul(uint a, uint b) internal returns (uint) {
    uint c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function safeDiv(uint a, uint b) internal returns (uint) {
    assert(b > 0);
    uint c = a / b;
    assert(a == b * c + a % b);
    return c;
  }

  function safeSub(uint a, uint b) internal returns (uint) {
    assert(b <= a);
    return a - b;
  }

  function safeAdd(uint a, uint b) internal returns (uint) {
    uint c = a + b;
    assert(c>=a && c>=b);
    return c;
  }

  function max64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a >= b ? a : b;
  }

  function min64(uint64 a, uint64 b) internal constant returns (uint64) {
    return a < b ? a : b;
  }

  function max256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a >= b ? a : b;
  }

  function min256(uint256 a, uint256 b) internal constant returns (uint256) {
    return a < b ? a : b;
  }

  function assert(bool assertion) internal {
    if (!assertion) {
      throw;
    }
  }
}


Remove setProof in OraclizeVerifier - not sure of breakage cause, but not currently used

pragma solidity ^0.4.11;

import "./Verifier.sol";
import "./Verifiable.sol";

import "../../installed_contracts/oraclize/contracts/usingOraclize.sol";

/*
 * @title Verifier contract that uses Oraclize for off-chain computation
 */
contract OraclizeVerifier is Verifier, usingOraclize {
    string public verificationCodeHash;

    // Stores parameters for an Oraclize query
    struct OraclizeQuery {
        uint256 jobId;
        uint256 claimId;
        uint256 segmentNumber;
        string transcodedDataHash;
        address callbackContract;
    }

    // Stores active Oraclize queries
    mapping (bytes32 => OraclizeQuery) oraclizeQueries;

    // Check if sender is Oraclize
    modifier onlyOraclize() {
        require(msg.sender == oraclize_cbAddress());
        _;
    }

    // Check if sufficient funds for Oraclize computation
    modifier sufficientOraclizeFunds() {
        require(oraclize_getPrice("computation") <= msg.value);
        _;
    }

    function OraclizeVerifier() {
        // OAR used for testing purposes
        OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
        // Set verification code hash
        verificationCodeHash = "QmPu23REr93Mfv7m9NPdFLMZz7PzHE1LaXvn4AmQCQgR3u";
    }

    event OraclizeCallback(uint256 indexed jobId, uint256 indexed claimId, uint256 indexed segmentNumber, bytes proof, bool result);

    /*
     * @dev Verify implementation that creates an Oraclize computation query
     * @param _jobId Job identifier
     * @param _segmentNumber Segment being verified for job
     * @param _code Content-addressed storage hash of binary to execute off-chain
     * @param _dataHash Content-addressed storage hash of input data of segment
     * @param _transcodedDataHash Hash of transcoded segment data
     * @param _callbackContract Address of Verifiable contract to call back
     */
    function verify(
        uint256 _jobId,
        uint256 _claimId,
        uint256 _segmentNumber,
        string _dataHash,
        string _transcodedDataHash,
        address _callbackContract
    )
        external
        payable
        sufficientOraclizeFunds
        returns (bool)
    {
        // Create Oraclize query
        string memory mVerificationCodeHash = verificationCodeHash;
        bytes32 queryId = oraclize_query("computation", [mVerificationCodeHash, _dataHash], 3000000);

        // Store Oraclize query parameters
        oraclizeQueries[queryId].jobId = _jobId;
        oraclizeQueries[queryId].claimId = _claimId;
        oraclizeQueries[queryId].segmentNumber = _segmentNumber;
        oraclizeQueries[queryId].transcodedDataHash = _transcodedDataHash;
        oraclizeQueries[queryId].callbackContract = _callbackContract;

        return true;
    }

    /*
     * @dev Callback function invoked by Oraclize to return result of off-chain computation
     * @param _queryId Oraclize query identifier
     * @param _result Result of Oraclize computation
     */
    function __callback(bytes32 _queryId, string _result, bytes _proof) onlyOraclize {
        OraclizeQuery memory oc = oraclizeQueries[_queryId];

        // Check if transcoded data hash returned by Oraclize matches originally submitted transcoded data hash
        if (strCompare(oc.transcodedDataHash, _result) == 0) {
            // Notify callback contract of successful verification
            Verifiable(oc.callbackContract).receiveVerification(oc.jobId, oc.claimId, oc.segmentNumber, true);
            OraclizeCallback(oc.jobId, oc.claimId, oc.segmentNumber, _proof, true);
        } else {
            // Notify callback contract of failed verification
            Verifiable(oc.callbackContract).receiveVerification(oc.jobId, oc.claimId, oc.segmentNumber, false);
            OraclizeCallback(oc.jobId, oc.claimId, oc.segmentNumber, _proof, false);
        }

        // Remove Oraclize query
        delete oraclizeQueries[_queryId];
    }
}

pragma solidity ^0.4.11;

import "./Verifier.sol";
import "./Verifiable.sol";

import "../../installed_contracts/oraclize/contracts/usingOraclize.sol";

/*
 * @title Verifier contract that uses Oraclize for off-chain computation
 */
contract OraclizeVerifier is Verifier, usingOraclize {
    string public verificationCodeHash;

    // Stores parameters for an Oraclize query
    struct OraclizeQuery {
        uint256 jobId;
        uint256 claimId;
        uint256 segmentNumber;
        string transcodedDataHash;
        address callbackContract;
    }

    // Stores active Oraclize queries
    mapping (bytes32 => OraclizeQuery) oraclizeQueries;

    // Check if sender is Oraclize
    modifier onlyOraclize() {
        require(msg.sender == oraclize_cbAddress());
        _;
    }

    // Check if sufficient funds for Oraclize computation
    modifier sufficientOraclizeFunds() {
        if (oraclize_getPrice("computation") > msg.value) throw;
        _;
    }

    function OraclizeVerifier() {
        // OAR used for testing purposes
        OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
        // Set Oraclize proof
        oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
        // Set verification code hash
        verificationCodeHash = "QmPu23REr93Mfv7m9NPdFLMZz7PzHE1LaXvn4AmQCQgR3u";
    }

    event OraclizeCallback(uint256 indexed jobId, uint256 indexed claimId, uint256 indexed segmentNumber, bytes proof, bool result);

    /*
     * @dev Verify implementation that creates an Oraclize computation query
     * @param _jobId Job identifier
     * @param _segmentNumber Segment being verified for job
     * @param _code Content-addressed storage hash of binary to execute off-chain
     * @param _dataHash Content-addressed storage hash of input data of segment
     * @param _transcodedDataHash Hash of transcoded segment data
     * @param _callbackContract Address of Verifiable contract to call back
     */
    function verify(
        uint256 _jobId,
        uint256 _claimId,
        uint256 _segmentNumber,
        string _dataHash,
        string _transcodedDataHash,
        address _callbackContract
    )
        external
        payable
        sufficientOraclizeFunds
        returns (bool)
    {
        // Create Oraclize query
        string memory mVerificationCodeHash = verificationCodeHash;
        bytes32 queryId = oraclize_query("computation", [mVerificationCodeHash, _dataHash], 3000000);

        // Store Oraclize query parameters
        oraclizeQueries[queryId].jobId = _jobId;
        oraclizeQueries[queryId].claimId = _claimId;
        oraclizeQueries[queryId].segmentNumber = _segmentNumber;
        oraclizeQueries[queryId].transcodedDataHash = _transcodedDataHash;
        oraclizeQueries[queryId].callbackContract = _callbackContract;

        return true;
    }

    /*
     * @dev Callback function invoked by Oraclize to return result of off-chain computation
     * @param _queryId Oraclize query identifier
     * @param _result Result of Oraclize computation
     */
    function __callback(bytes32 _queryId, string _result, bytes _proof) onlyOraclize {
        OraclizeQuery memory oc = oraclizeQueries[_queryId];

        // Check if transcoded data hash returned by Oraclize matches originally submitted transcoded data hash
        if (strCompare(oc.transcodedDataHash, _result) == 0) {
            // Notify callback contract of successful verification
            Verifiable(oc.callbackContract).receiveVerification(oc.jobId, oc.claimId, oc.segmentNumber, true);
            OraclizeCallback(oc.jobId, oc.claimId, oc.segmentNumber, _proof, true);
        } else {
            // Notify callback contract of failed verification
            Verifiable(oc.callbackContract).receiveVerification(oc.jobId, oc.claimId, oc.segmentNumber, false);
            OraclizeCallback(oc.jobId, oc.claimId, oc.segmentNumber, _proof, false);
        }

        // Remove Oraclize query
        delete oraclizeQueries[_queryId];
    }
}