-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathuseNetwork.tsx
92 lines (73 loc) · 2.24 KB
/
useNetwork.tsx
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
import { useState, useEffect } from 'react';
import swarm from 'webrtc-swarm';
import signalhub from 'signalhub';
import { Vote, Block } from './blockchain';
const hub = signalhub('blockchain-swarm', ['http://localhost:8080']);
interface PeerExchangeFormat {
infoType: 'VOTE' | 'BLOCK';
value: Vote | Block;
}
interface PeerList {
[key: string]: {
send: Function;
on: Function;
[key: string]: any;
};
}
export default function useNetwork(
voteSub: Function,
blockSub: Function
): [PeerList, (vote: Vote) => void, (blocks: Block[]) => void] {
const [peers, setPeers] = useState<Partial<PeerList>>({});
function sendVote(vote: Vote) {
voteSub(vote); // Send to self
Object.values(peers).forEach(peer => {
peer.send(JSON.stringify({ infoType: 'VOTE', value: vote }));
});
}
function sendBlock(blocks: Block[]) {
blockSub(blocks);
Object.values(peers).forEach(peer => {
peer.send(JSON.stringify({ infoType: 'BLOCK', value: blocks }));
});
}
useEffect(() => {
var sw = swarm(hub);
function connectPeer(peer, id) {
setPeers(peers => ({ ...peers, [id]: peer }));
console.group('swarm-connect');
console.log('connected to a new peer:', id);
console.log('total peers:', sw.peers.length);
console.groupEnd();
peer.on('data', (data: PeerExchangeFormat) => {
const { infoType, value } = JSON.parse(data.toString());
switch (infoType) {
case 'BLOCK':
return blockSub(value); // send block
case 'VOTE':
return voteSub(value); //send vote
}
});
}
function disconnectPeer(peer, id) {
console.group('swarm-disconnect');
console.log('disconnected from peer:', id);
console.log('total peers:', sw.peers.length);
console.groupEnd();
setPeers(peers => {
var newPeerList = Object.assign({}, peers);
delete newPeerList[id];
return newPeerList;
});
}
sw.on('peer', connectPeer);
sw.on('disconnect', disconnectPeer);
return () => {
sw.removeListener('peer', connectPeer);
sw.removeListener('disconnect', disconnectPeer);
sw = {};
setPeers({});
};
}, []);
return [peers, sendVote, sendBlock];
}