-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.coffee
61 lines (46 loc) · 1.82 KB
/
peer.coffee
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
Biscuit = require './biscuit'
BisquePeer = class BisquePeer
initializeBisque: (reward_threshold, debug=false) ->
@biscuit_creators = {}
@biscuit_deliverers = {}
@debug = debug
@reward_threshold = reward_threshold
@buildDenominator()
buildDenominator: ->
denominator = 0
_i = @reward_threshold
while _i > 0
denominator += _i
_i--
@denominator = denominator
onMessage: (message) ->
console.log "[#{@username}: i got a message", message
_num_deliverers = @messages[message.id].peers?.length
if _num_deliverers < @reward_threshold
_b = new Biscuit 1/Math.pow(2,_num_deliverers-1), message.id, @id
@sendBiscuit _b, message.from
onBiscuit: (biscuit) ->
console.log "[#{@username}: i got a biscuit", biscuit
{N, message_id, creator_id, from} = biscuit
@biscuit_creators[creator_id] ||= []
@biscuit_creators[creator_id].push biscuit
@biscuit_deliverers[from] || = []
@biscuit_deliverers[from].push biscuit
deliverers = @findDeliverers message_id, @reward_threshold
deliverers.map (d_id, _i) =>
i = @reward_threshold - _i
_N = (i * N) / @denominator
_b = new Biscuit _N, message_id, creator_id
@sendBiscuit _b, d_id
if @debug
@reportState()
findDeliverers: (message_id, i) ->
(@messages[message_id]?.peers || []).slice(0, i-1)
sendBiscuit: (biscuit, peer_id) ->
peer = @peers[peer_id]
biscuit.from = @id
@sendMessageToPeer {kind: 'biscuit', biscuit}, peer_id
reportState: ->
# TODO: post my state to the UI
# {biscuit_creators, biscuit_deliverers, reward_threshold, messages}
module.exports = BisquePeer