-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap-node.js
300 lines (273 loc) · 8.77 KB
/
bootstrap-node.js
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"use strict";
// CUSTOMIZE THESE VARIABLES
const DB_NAME = "orbitdbchatipfs987333979"; // main db for messages
const DB_NAME_CONTROL = "db-control9535527"; // db controller info from private subscriptions y private channels
const IPFS = require("ipfs");
const OrbitDB = require("orbit-db");
const { encrypt, decrypt } = require("./encryption.js");
const PUBSUB_CHANNEL = "ipfsObitdb-chat";
let onlineNodes = {};
let orbitdb;
let dbControl;
let gettingPassword = true;
let latestMessagesDecrypted = [];
// Pass the encryption password in via environment variable.
let ENCRYPTION_PASSWORD;
if (!process.env.CHAT_ENCRYPTION_PASS) {
console.log(
`Please set the encryption password via the CHAT_ENCRYPTION_PASS environment variable before running this app.`
);
return;
} else {
ENCRYPTION_PASSWORD = process.env.CHAT_ENCRYPTION_PASS;
}
// starting ipfs node
console.log("Starting...!");
const ipfs = new IPFS({
repo: "./orbitdb/examples/ipfs",
start: true,
EXPERIMENTAL: {
pubsub: true
},
// config: {
// Addresses: {
// Swarm: ["/ip4/0.0.0.0/tcp/8006", "/ip4/127.0.0.1/tcp/8007/ws"],
// API: "/ip4/127.0.0.1/tcp/8008",
// Gateway: "/ip4/127.0.0.1/tcp/8009"
// }
// },
relay: {
enabled: true, // enable circuit relay dialer and listener
hop: {
enabled: true // enable circuit relay HOP (make this node a relay)
}
}
});
ipfs.on("error", err => console.error(err));
ipfs.on("replicated", () => {
console.log(`replication event fired`);
});
ipfs.on("ready", async () => {
console.log(`ipfs ready.`);
// init orbitDb
let db;
const optionsDb = {
directory: "./orbitdb/examples/eventlog"
};
try {
const access = {
accessController: {
write: ["*"],
overwrite: true
}
};
// create main db , global chat messages
orbitdb = await OrbitDB.createInstance(ipfs, optionsDb);
db = await orbitdb.eventlog(DB_NAME, access);
await db.load();
console.log(`db id: ${db.id}`);
// setInterval(async function() {
// const peers = await ipfs.swarm.peers()
// console.log(`peers: ${JSON.stringify(peers,null,2)}`)
// }, 5000)
} catch (e) {
console.error(e);
process.exit(1);
}
try {
const access = {
// Give write access to everyone
write: ["*"]
};
/* create db for control info
This DB controls the information between channels of peer to peer nodes
*/
dbControl = await orbitdb.eventlog(DB_NAME_CONTROL, access);
await dbControl.load();
//console.log(`dbControl id: ${db.id}`);
} catch (e) {
console.error(e);
process.exit(1);
}
// get encryption password from console
//getPasswordEncryption()
//subscribe to master pubsub channel
ipfs.pubsub.subscribe(PUBSUB_CHANNEL, data => {
const jsonData = JSON.parse(data.data.toString());
const key = data.from.toString();
/*
All the nodes connected send a message each second
to keep control of the online nodes
*/
if (jsonData.status === "online" && jsonData.username != "system") {
const userData = {
username: jsonData.username ? jsonData.username : "",
date: new Date(),
keyId: key
};
if (onlineNodes[data.from] == undefined) {
console.log("system", `${data.from} joined the chat`);
}
onlineNodes[data.from] = userData;
}
//Node request to generate a private channel with another node
if (jsonData.status === "requestChat") {
subscribe(jsonData.channelName, jsonData.dbName);
queryControl(
jsonData.peer1,
jsonData.peer2,
jsonData.channelName,
jsonData.dbName,
jsonData.dbId
);
}
});
// sending online nodes list in master pubsub channel
setInterval(() => {
const msg = { onlineNodes: onlineNodes };
const msgEncoded = Buffer.from(JSON.stringify(msg));
ipfs.pubsub.publish(PUBSUB_CHANNEL, msgEncoded);
const msg2 = { status: "online", username: "system" };
const msgEncoded2 = Buffer.from(JSON.stringify(msg2));
ipfs.pubsub.publish(PUBSUB_CHANNEL, msgEncoded2);
//peers subscriptions to PUBSUB_CHANNEL
ipfs.pubsub.peers(PUBSUB_CHANNEL, (err, peerIds) => {
if (err) {
return console.error(
`failed to get peers subscribed to ${PUBSUB_CHANNEL}`,
err
);
}
//console.log(peerIds)
});
}, 1000);
// pull offline nodes from list
setInterval(() => {
const peers = Object.keys(onlineNodes);
peers.sort().forEach((peerID, i) => {
const timeLastSaw = onlineNodes[peerID].date;
const diff = (new Date() - timeLastSaw) / 1500;
if (diff > 5) {
delete onlineNodes[peerID];
console.log(`System ${peerID} left the chat`);
return;
}
});
}, 1000);
});
const subscribe = async (cnahhelName, dbname) => {
ipfs.pubsub.subscribe(cnahhelName, data => {
// console.log(data.from);
});
};
// Decrypting all db_control values
const getDataDecrypted = async arrayData => {
arrayData.map(async val => {
let decoded = await decrypt(val.payload.value, ENCRYPTION_PASSWORD);
latestMessagesDecrypted.push(JSON.parse(decoded));
});
};
//Control channels and db id's
const queryControl = async (from, to, channelName, dbName, dbID) => {
const access = {
accessController: {
write: ["*"],
overwrite: true
}
};
let chatData;
const latestMessages = dbControl.iterator({ limit: -1 }).collect();
await getDataDecrypted(latestMessages);
/*
Search for an existing channel and conversation info between two nodes
*/
for (let i = 0; i < latestMessagesDecrypted.length; i++) {
if (latestMessagesDecrypted[i].peer1 === from) {
if (latestMessagesDecrypted[i].peer2 === to) {
chatData = latestMessagesDecrypted[i];
}
} else if (latestMessagesDecrypted[i].peer1 === to) {
if (latestMessagesDecrypted[i].peer2 === from) {
chatData = latestMessagesDecrypted[i];
}
}
}
latestMessagesDecrypted = []; // reset latest Messages Decrypted array
// channel/room betwwen 2 peer exists
if (chatData) {
const entry2 = {
peer1: from, //node that emits the petition
peer2: to, //node that receives the petition
channelName: chatData.channelName, //name for pubsubchannel between peer1 and peer2
dbName: chatData.dbName, //name for private Orbitdb between peer1 and peer2
dbId: dbID, //id for replicate private Orbitdb between peer1 and peer2
exist: true,
pass: chatData.pass // pass for encrypt/decrypt this room db
};
const msgEncoded = Buffer.from(JSON.stringify(entry2));
ipfs.pubsub.publish(from, msgEncoded);
orbitdb.eventlog(entry2.dbName, access);
return chatData;
}
// channel betwwen 2 peer not exists. Create and add room info
try {
let newPassword = await generatePassword();
const entry = {
peer1: from, //node that emits the petition
peer2: to, //node that receives the petition
channelName: channelName, //name for pubsubchannel between peer1 and peer2
dbName: dbName, //name for private Orbitdb between peer1 and peer2
dbId: dbID, //id for replicate private Orbitdb between peer1 and peer2
exist: false,
pass: newPassword // pass for encrypt/decrypt this room db
};
// orbitdb.eventlog(entry.dbName, access);
//encrypting entry
const entryEncrypted = await encrypt(
JSON.stringify(entry),
ENCRYPTION_PASSWORD
);
//adding to db
await dbControl.add(entryEncrypted);
// sending to node that emits the petition
const msgEncoded = Buffer.from(JSON.stringify(entry));
ipfs.pubsub.publish(from, msgEncoded);
} catch (e) {
console.error(e);
process.exit(1);
}
};
const getPasswordEncryption = () => {
// get password for encrypt- console
var standard_input = process.openStdin();
process.stdin.setEncoding("utf8");
console.log("\n");
console.log("--------------------\n");
console.log("Insert Encryption Password.");
//
standard_input.on("data", async data => {
// console.clear();
// User input exit.
if (data === "exit\n") {
// Program exit.
console.log("User input complete, program exit.");
process.exit();
} else {
if (gettingPassword) {
ENCRYPTION_PASSWORD = data.replace(/(\r\n|\n|\r)/gm, ""); // remove /n from data
gettingPassword = false;
console.log("done!");
}
}
});
};
// Generate password.
const generatePassword = async () => {
let long = parseInt(Math.floor(Math.random() * 10 + 7)); //min 7 Characters
if (long > 10) long = 10; //max 10 Characters
let charts = "abcdefghijkmnpqrtuvwxyzABCDEFGHIJKLMNPQRTUVWXYZ2346789";
let pass = "";
for (let i = 0; i < long; i++)
pass += charts.charAt(Math.floor(Math.random() * charts.length));
return pass;
};