| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264 | 41×
41×
 
 
 
257×
255×
 
 
 
 
 
84×
1×
 
83×
 
 
82×
82×
82×
 
83×
15×
15×
15×
 
 
 
 
 
82×
2×
 
81×
79×
79×
79×
 
81×
 
14×
14×
14×
14×
 
 
 
 
3×
2×
1×
1×
1×
 
 
 
 
 
 
 
 
 
 
68×
 
66×
3×
 
 
64×
 
63×
63×
63×
63×
 
 
64×
11×
11×
 
 
 
 
6×
4×
2×
2×
2×
 
 
 
10×
10×
10×
 
 
10×
55×
53×
53×
53×
53×
4×
4×
4×
 
 
4×
 
49×
49×
 
 
 
 
10×
55×
49×
49×
 
 
 
 
 
68×
68×
68×
68×
 
68×
465×
465×
 
465×
465×
 
465×
465×
267×
267×
 
198×
198×
 
465×
465×
465×
465×
 
 
 
 
 
 
 
 
 
 
41×
41×
41×
41×
41×
 
14×
 
 
 
27×
27×
27×
27×
27×
27×
 
27×
27×
 
41×
41×
 
 
 
 
4×
4×
4×
4×
16×
10×
10×
 
 
4×
 
 
 
 
465×
462×
462×
462×
 
 
 
 
 
 
5×
27×
7×
7×
 
 
5×
3×
 
 
 
 
29×
157×
156×
 
 
 
 
 
11×
11×
11×
60×
58×
58×
 
 
11×
11×
 
11×
10×
10×
10×
 
 
 
1×
 
11× | pragma solidity ^0.4.23;
 
import "./Math.sol";
import "./Concept.sol";
import "./FathomToken.sol";
import "./AssessmentData.sol";
 
contract Assessment is AssessmentData {
 
    modifier onlyConcept() {
        Erequire(msg.sender == address(concept), 'Concept access only');
        _;
    }
 
    modifier onlyInStage(Stage _stage) {
        require(assessmentStage == _stage, 'Called during wrong assessment stage');
        _;
    }
 
    // called by an assessor to confirm and stake
    function confirmAssessor() public onlyInStage(Stage.Called) {
        // cancel if the assessment is past its startTime
        if (now > checkpoint) {
            return cancelAssessment();
        }
        if (assessorStage[msg.sender] == Stage.Called &&
            assessors.length < size &&
            fathomToken.takeBalance(msg.sender, address(this), cost, concept)) {
            assessors.push(msg.sender);
            assessorStage[msg.sender] = Stage.Confirmed;
            fathomToken.notification(msg.sender, FathomToken.Note.ConfirmedAsAssessor);
        }
        if (assessors.length == size) {
            notifyAssessors(uint(Stage.Confirmed), FathomToken.Note.AssessmentHasBegun);
            fathomToken.notification(assessee, FathomToken.Note.AssessmentHasBegun);
            assessmentStage = Stage.Confirmed;
        }
    }
 
    //called by an assessor to commit a hash of their score //TODO explain in more detail what's happening
    function commit(bytes32 _hash) public onlyInStage(Stage.Confirmed) {
        if (now > endTime) {
            burnStakes(Stage.Confirmed);
        }
        if (assessorStage[msg.sender] == Stage.Confirmed) {
            commits[msg.sender] = _hash;
            assessorStage[msg.sender] = Stage.Committed;
            done++; //Increases done by 1 to help progress to the next assessment stage.
        }
        if (done == size) {
            //set checkpoint to end of 12 hour challenge period after which scores can be revealed
            checkpoint = now + CHALLENGE_PERIOD;
            notifyAssessors(uint(Stage.Committed), FathomToken.Note.RevealScore);
            done = 0; //Resets the done counter
            assessmentStage = Stage.Committed;
        }
    }
 
    function steal(int128 _score, string _salt, address assessor) public {
        if (assessorStage[assessor] == Stage.Committed) {
            if (commits[assessor] == keccak256(abi.encodePacked(_score, _salt))) {
                fathomToken.transfer(msg.sender, cost/2);
                assessorStage[assessor] = Stage.Burned;
                size--;
            }
        }
    }
 
    //@purpose: called by assessors to reveal their own commits or others
    // must be called between 12 hours after the latest commit and 24 hours after the
    // end of the assessment. If the last commit happens during at the last possible
    // point in time (right before endtime), this period will be 12hours
    function reveal(int128 _score, string _salt) public onlyInStage(Stage.Committed) {
        // scores can only be revealed after the challenge period has passed
        require(now > checkpoint, 'Challenge period must be over');
        // If the time to reveal has passed, burn all unrevealed assessors
        if (now > endTime + 24 hours) {
            burnStakes(Stage.Committed);
        }
 
        if (assessorStage[msg.sender] == Stage.Committed &&
            commits[msg.sender] == keccak256(abi.encodePacked(_score, _salt))) {
            scores[msg.sender] = _score;
            salt = salt ^ (keccak256(bytes(_salt)));
            assessorStage[msg.sender] = Stage.Done;
            done++;
        }
 
        if (done == size) {
            assessmentStage = Stage.Done;
            calculateResult();
        }
    }
 
    function addData(bytes _data) public {
        require(msg.sender == assessee || assessorStage[msg.sender] > Stage.Called, 'Must be assessee or confirmed assessor');
        require(assessmentStage < Stage.Committed, 'Deadline for adding data has passed');
        bytes memory oldData = data[msg.sender];
        data[msg.sender] = _data;
        emit DataChanged(msg.sender, oldData, _data);
    }
 
    function payout(uint greatestClusterLength) public onlyInStage(Stage.Done) {
        uint dissentBonus = 0;
        bool[] memory inAssessor = new bool[](assessors.length);
        uint[] memory inAssessorPayout = new uint[](assessors.length);
        // pay out dissenting assessors their reduced stake, set their Stage to dissent
        // and save how much stake to redistribute to whom
        for (uint i = 0; i < assessors.length; i++) {
            if (assessorStage[assessors[i]] == Stage.Done) {
                uint payoutValue;
                bool dissenting;
                (payoutValue, dissenting) = Math.getPayout(Math.abs(scores[assessors[i]] - finalScore), cost, CONSENT_RADIUS);
                if (dissenting) {
                    assessorStage[assessors[i]] = Stage.Dissent;
                    dissentBonus += cost - payoutValue;
                    Iif (payoutValue > 0) {
                        fathomToken.transfer(assessors[i], payoutValue);
                    }
                    fathomToken.notification(assessors[i], FathomToken.Note.ConsensusReached);
                } else {
                    inAssessor[i] = true;
                    inAssessorPayout[i] = payoutValue;
                }
            }
        }
        // pay out the majority-assessors their share of stake + the remainders of any dissenting assessors
        for (uint j = 0; j < inAssessorPayout.length; j++) {
            if (inAssessor[j]) {
                fathomToken.transfer(assessors[j], inAssessorPayout[j] + dissentBonus/greatestClusterLength);
                fathomToken.notification(assessors[j], FathomToken.Note.ConsensusReached);
            }
        }
    }
 
    function callRandomMembers(uint _seed, uint amount, address _concept) internal returns(uint successfullyCalled){
      uint seed = _seed;
      Concept concept = Concept(_concept);
      address[] memory availableMembers = concept.getActiveBucket();
      uint length = availableMembers.length;
 
      for(uint i = 0; i < amount; i++) {
        uint index1 = Math.getRandom(seed, length - 1 );
        uint index2 = Math.getRandom(seed*2, length - 1);
 
        uint weight1 = concept.getWeight(availableMembers[index1]);
        uint weight2 = concept.getWeight(availableMembers[index2]);
 
        address calledAssessor;
        if (weight1 >= weight2) {
          calledAssessor = availableMembers[index1];
          availableMembers[index1] = availableMembers[length - 1];
        } else {
          calledAssessor = availableMembers[index2];
          availableMembers[index2] = availableMembers[length - 1];
        }
        availableMembers[length -1] = calledAssessor;
        if (addAssessorToPool(calledAssessor)) successfullyCalled += 1;
        seed += 10;
        length--;
      }
    }
 
    /*
      Assembles a pool of assessors from assessed concept
      @param: uint seed = the seed number for random number generation
      @param: address _concept = the concept being called from
      @param: uint _size = the desired size of the assessment
    */
    function setAssessorPool(uint seed, address _concept, uint _size) public onlyConcept() {
        uint toBeCalled = (_size * ASSESSORPOOL_SIZEFACTOR) / 10;
        uint totalCalled;
        Concept assessedConcept = Concept(_concept);
        uint availableHere = (assessedConcept.getAvailableMemberLength() * MEMBERCALL_CEILING_FACTOR) / 10;
        if (availableHere >= toBeCalled) {
            //Call from this concept num assessors
            totalCalled += callRandomMembers(seed, toBeCalled, _concept);
        }
        else {
            // check whether parents have enough members
            uint availableViaParents;
            for(uint k = 0; k < assessedConcept.getParentsLength(); k++) {
                Concept parent = Concept(assessedConcept.parents(k));
                uint availableInParent = (((parent.getAvailableMemberLength() * MEMBERCALL_CEILING_FACTOR) / 10) * assessedConcept.propagationRates(k)) / 1000;
                availableViaParents += availableInParent;
                totalCalled += callRandomMembers(seed + k, availableInParent, address(parent));
            }
            Erequire(availableHere + availableViaParents >= toBeCalled, 'Not enough assessors in parent concepts');
            totalCalled += callRandomMembers(seed + 4224, availableHere, _concept);
        }
        Erequire(totalCalled >= MIN_ASSESSMENT_SIZE, 'Too few assessors could be called');
        assessmentStage = Stage.Called;
    }
 
    // ends the assessment, refunds the assessee and all assessors who have not been burned
    function cancelAssessment() private {
        uint assesseeRefund = assessmentStage == Stage.Called ? cost * size : cost * assessors.length;
        fathomToken.transfer(assessee, assesseeRefund);
        fathomToken.notification(assessee, FathomToken.Note.AssessmentCancelled);
        for (uint i = 0; i < assessors.length; i++) {
            if (assessorStage[assessors[i]] != Stage.Burned) {
                fathomToken.transfer(assessors[i], cost);
                fathomToken.notification(assessors[i], FathomToken.Note.AssessmentCancelled);
            }
        }
        selfdestruct(address(concept));
    }
 
    //adds a user to the pool eligible to accept an assessment
    function addAssessorToPool(address assessor) private returns(bool) {
        if (assessor != assessee && assessorStage[assessor] == Stage.None) {
          fathomToken.notification(assessor, FathomToken.Note.CalledAsAssessor);
            assessorStage[assessor] = Stage.Called;
            return true;
        }
    }
 
    // burns stakes of all assessors who are in a certain stage Stage
    // if afterwards, the size is below 5, the assessment is cancelled
    function burnStakes(Stage _stage) private {
        for (uint i = 0; i < assessors.length; i++) {
            if (assessorStage[assessors[i]] == _stage) {
                assessorStage[assessors[i]] = Stage.Burned;
                size--;
            }
        }
        if (size < 5) {
            cancelAssessment();
        }
    }
 
    function notifyAssessors(uint _stage,  FathomToken.Note _topic) private {
        for (uint i=0; i < assessors.length; i++) {
            if (uint(assessorStage[assessors[i]]) == _stage) {
                fathomToken.notification(assessors[i], _topic);
            }
        }
    }
 
    function calculateResult() private onlyInStage(Stage.Done) {
        int[] memory finalScores = new int[](done);
        uint idx =0;
        for (uint j = 0; j < assessors.length; j++) {
            if (assessorStage[assessors[j]] == Stage.Done) {
                finalScores[idx] = scores[assessors[j]];
                idx++;
            }
        }
        uint greatestClusterLength;
        (finalScore, greatestClusterLength) = Math.getFinalScore(finalScores, CONSENT_RADIUS);
        // check if a majority of assessors found a point of consensus
        if (greatestClusterLength > done/2) {
            payout(greatestClusterLength);
            Eif (finalScore > 0) {
                concept.addMember(assessee, uint(finalScore) * greatestClusterLength);
            }
        } else {
            // set final Score to zero to signal no consensus
            finalScore = 0;
        }
        fathomToken.notification(assessee, FathomToken.Note.AssessmentFinished);
    }
}
  |