Boradcasting Events to Peers Working

This commit is contained in:
Luis Fernando Molina committed 2021-11-07 14:12:11 +01:00
1 parent 05ad894821
commit 5a281b5de0
4 files changed
+68 -141

No files matched your search

@@ -136,8 +136,8 @@ exports.newNetworkModulesWebSocketsInterface = function newNetworkModulesWebSock
}
}
if (response.result === 'Ok' && JSON.parse(messageHeader.payload).requestType === 'Event') {
broadcastToPeers(message, caller)
broadcastToClients(message, caller)
broadcastToPeers(messageHeader, caller)
broadcastToClients(messageHeader, caller)
}
break
}
@@ -516,7 +516,7 @@ exports.newNetworkModulesWebSocketsInterface = function newNetworkModulesWebSock
}
}
function broadcastToPeers(message, caller) {
function broadcastToPeers(messageHeader, caller) {
/*
The Boradcast to network peers is not done via
the network peers incomming connections, but
@@ -526,14 +526,19 @@ exports.newNetworkModulesWebSocketsInterface = function newNetworkModulesWebSock
if (caller.role === 'Network Peer') {
callerIdToAVoid = caller.node.id
}
for (let i = 0; i < NT.networkNode.p2pNetworkPeers.outgoingConnectedPeers.length; i++) {
let networkPeer = NT.networkNode.p2pNetworkPeers.outgoingConnectedPeers[i]
if (networkPeer.p2pNetworkNode.node.id === callerIdToAVoid) { continue }
networkPeer.socket.send(message)
for (let i = 0; i < NT.networkNode.p2pNetworkPeers.peers.length; i++) {
let peer = NT.networkNode.p2pNetworkPeers.peers[i]
if (peer.p2pNetworkNode.node.id === callerIdToAVoid) { continue }
peer.webSocketsClient.sendMessage(messageHeader.payload)
.catch(onError)
function onError() {
console.log('[ERROR] Web Sockets Interface -> broadcastToPeers -> Sending Message Failed.')
}
}
}
function broadcastToClients(message, caller) {
function broadcastToClients(messageHeader, caller) {
let callerIdToAVoid
if (caller.role === 'Network Client') {
callerIdToAVoid = caller.socket.id
@@ -541,7 +546,12 @@ exports.newNetworkModulesWebSocketsInterface = function newNetworkModulesWebSock
for (let i = 0; i < thisObject.networkClients.length; i++) {
let networkClient = thisObject.networkClients[i]
if (networkClient.socket.id === callerIdToAVoid) { continue }
networkClient.socket.send(message)
networkClient.socket.send(messageHeader.payload)
.catch(onError)
function onError() {
console.log('[ERROR] Web Sockets Interface -> broadcastToPeers -> Sending Message Failed.')
}
}
}
+18 -13
View File
@@ -1,9 +1,9 @@
exports.newNetworkModulesP2PNetworkPeers = function newNetworkModulesP2PNetworkPeers() {
/*
This module holds the P2P Nodes we are coonected to and that are connected to us.
This module holds the P2P Nodes we are coonected to.
*/
let thisObject = {
outgoingConnectedPeers: undefined,
peers: undefined,
/* Framework Functions */
initialize: initialize,
@@ -16,13 +16,13 @@ exports.newNetworkModulesP2PNetworkPeers = function newNetworkModulesP2PNetworkP
return thisObject
function finalize() {
thisObject.outgoingConnectedPeers = undefined
thisObject.peers = undefined
clearInterval(intervalIdConnectToPeers)
}
async function initialize() {
thisObject.outgoingConnectedPeers = []
thisObject.peers = []
connectToPeers()
intervalIdConnectToPeers = setInterval(connectToPeers, RECONNECT_DELAY);
@@ -31,11 +31,16 @@ exports.newNetworkModulesP2PNetworkPeers = function newNetworkModulesP2PNetworkP
async function connectToPeers() {
if (thisObject.outgoingConnectedPeers.count >= global.env.P2P_NETWORK_NODE_MAX_OUTGOING_PEERS) { return }
if (thisObject.peers.count >= global.env.P2P_NETWORK_NODE_MAX_OUTGOING_PEERS) { return }
for (let i = 0; i < NT.networkNode.p2pNetwork.p2pNodesToConnect.length; i++) {
if (thisObject.outgoingConnectedPeers.count >= global.env.P2P_NETWORK_NODE_MAX_OUTGOING_PEERS) { break }
let peer = {}
if (thisObject.peers.count >= global.env.P2P_NETWORK_NODE_MAX_OUTGOING_PEERS) { break }
let peer = {
p2pNetworkNode: undefined,
webSocketsClient: undefined
}
peer.p2pNetworkNode = NT.networkNode.p2pNetwork.p2pNodesToConnect[i]
if (isOutgoingConnectedPeer(peer) === true) { continue }
peer.webSocketsClient = SA.projects.network.modules.webSocketsNetworkClient.newNetworkModulesWebSocketsNetworkClient()
@@ -44,7 +49,7 @@ exports.newNetworkModulesP2PNetworkPeers = function newNetworkModulesP2PNetworkP
.catch(onError)
function addPeer() {
thisObject.outgoingConnectedPeers.push(peer)
thisObject.peers.push(peer)
}
function onError(err) {
@@ -56,10 +61,10 @@ exports.newNetworkModulesP2PNetworkPeers = function newNetworkModulesP2PNetworkP
}
function onConnectionClosed(webSocketsClientId) {
for (let i = 0; i < thisObject.outgoingConnectedPeers.length; i++) {
let connectedPeer = thisObject.outgoingConnectedPeers[i]
for (let i = 0; i < thisObject.peers.length; i++) {
let connectedPeer = thisObject.peers[i]
if (connectedPeer.webSocketsClient.id === webSocketsClientId) {
thisObject.outgoingConnectedPeers.splice(i, 1)
thisObject.peers.splice(i, 1)
return
}
}
@@ -67,8 +72,8 @@ exports.newNetworkModulesP2PNetworkPeers = function newNetworkModulesP2PNetworkP
}
function isOutgoingConnectedPeer(peer) {
for (let i = 0; i < thisObject.outgoingConnectedPeers.length; i++) {
let connectedPeer = thisObject.outgoingConnectedPeers[i]
for (let i = 0; i < thisObject.peers.length; i++) {
let connectedPeer = thisObject.peers[i]
if (connectedPeer.p2pNetworkNode.node.id === peer.p2pNetworkNode.node.id) {
return true
}
@@ -2,7 +2,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
let thisObject = {
id: undefined,
socketClient: undefined,
socket: undefined,
isConnected: undefined,
host: undefined,
port: undefined,
@@ -22,8 +22,8 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
return thisObject
function finalize() {
thisObject.socketClient.close()
thisObject.socketClient = undefined
thisObject.socket.close()
thisObject.socket = undefined
thisObject.id = undefined
thisObject.isConnected = undefined
thisObject.host = undefined
@@ -52,7 +52,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
thisObject.host = JSON.parse(thisObject.p2pNetworkNode.node.config).host
thisObject.port = JSON.parse(thisObject.p2pNetworkNode.node.config).webSocketsPort
thisObject.socketClient = new SA.nodeModules.ws('ws://' + thisObject.host + ':' + thisObject.port)
thisObject.socket = new SA.nodeModules.ws('ws://' + thisObject.host + ':' + thisObject.port)
await setUpWebSocketClient()
console.log('Websockets Client Connected to Network Node via Web Sockets ................ Connected to ' + thisObject.p2pNetworkNode.userProfile.userProfileHandle + ' -> ' + thisObject.p2pNetworkNode.node.name + ' -> ' + thisObject.host + ':' + thisObject.port)
@@ -67,9 +67,9 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
try {
thisObject.socketClient.onopen = () => { onConnectionOpened() }
thisObject.socketClient.onclose = () => { onConnectionClosed() }
thisObject.socketClient.onerror = err => { onError(err) }
thisObject.socket.onopen = () => { onConnectionOpened() }
thisObject.socket.onclose = () => { onConnectionClosed() }
thisObject.socket.onerror = err => { onError(err) }
function onConnectionOpened() {
@@ -93,7 +93,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
it's own identity, and later we will sign it's own handle
to prove ours.
*/
thisObject.socketClient.onmessage = socketMessage => { stepOneResponse(socketMessage) }
thisObject.socket.onmessage = socketMessage => { stepOneResponse(socketMessage) }
callerTimestamp = (new Date()).valueOf()
@@ -105,7 +105,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
callerNode: JSON.stringify(thisObject.p2pNetworkIdentity.node),
step: 'One'
}
thisObject.socketClient.send(JSON.stringify(message))
thisObject.socket.send(JSON.stringify(message))
}
function stepOneResponse(socketMessage) {
@@ -190,7 +190,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
Here we will sign a message with the Network Node profile
handle and timestamp to prove our own identity.
*/
thisObject.socketClient.onmessage = socketMessage => { stepTwoResponse(socketMessage) }
thisObject.socket.onmessage = socketMessage => { stepTwoResponse(socketMessage) }
let signature = web3.eth.accounts.sign(JSON.stringify(signedMessage), SA.secrets.map.get(global.env.DESKTOP_APP_SIGNING_ACCOUNT).privateKey)
@@ -199,7 +199,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
signature: JSON.stringify(signature),
step: 'Two'
}
thisObject.socketClient.send(JSON.stringify(message))
thisObject.socket.send(JSON.stringify(message))
}
function stepTwoResponse(socketMessage) {
@@ -215,7 +215,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
Network Node and from now on, all response messages will be received
at this following function.
*/
thisObject.socketClient.onmessage = socketMessage => { onMenssage(socketMessage) }
thisObject.socket.onmessage = socketMessage => { onMenssage(socketMessage) }
resolve()
}
}
@@ -256,7 +256,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
function sendSocketMessage(resolve, reject) {
if (thisObject.socketClient.readyState !== 1) { // 1 means connected and ready.
if (thisObject.socket.readyState !== 1) { // 1 means connected and ready.
console.log('[ERROR] Web Sockets Client -> sendMessage -> Cannot send message while connection is closed.')
reject('Websockets Connection Not Ready.')
return
@@ -268,7 +268,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
payload: message
}
onMessageFunctionsMap.set(socketMessage.messageId, onMenssageFunction)
thisObject.socketClient.send(
thisObject.socket.send(
JSON.stringify(socketMessage)
)
@@ -312,7 +312,7 @@ exports.newNetworkModulesWebSocketsNetworkClient = function newNetworkModulesWeb
} catch (err) {
console.log('[ERROR] Web Sockets Client -> onMenssage -> message = ' + message)
console.log('[ERROR] Web Sockets Client -> onMenssage -> err.stack = ' + err.stack)
thisObject.socketClient.close()
thisObject.socket.close()
return
}
@@ -23,14 +23,14 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
}
async function messageReceived(message, userProfile) {
async function messageReceived(message) {
let messageHeader
try {
messageHeader = JSON.parse(message)
} catch (err) {
let response = {
result: 'Error',
message: 'Client Interface message Not Correct JSON Format.'
message: 'Peer Interface message Not Correct JSON Format.'
}
return response
}
@@ -38,7 +38,7 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
if (messageHeader.requestType === undefined) {
let response = {
result: 'Error',
message: 'Client Interface requestType Not Provided.'
message: 'Peer Interface requestType Not Provided.'
}
return response
}
@@ -46,22 +46,26 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
if (messageHeader.requestType !== 'Event' && messageHeader.requestType !== 'Query') {
let response = {
result: 'Error',
message: 'Client Interface requestType Not Supported.'
message: 'Peer Interface requestType Not Supported.'
}
return response
}
switch (messageHeader.requestType) {
case 'Event': {
return await eventReceived(messageHeader.eventMessage, userProfile)
return await eventReceived(messageHeader.eventMessage)
}
case 'Query': {
return await queryReceived(messageHeader.queryMessage, userProfile)
let response = {
result: 'Error',
message: 'Peer Interface requestType Query Not Supported.'
}
return response
}
}
}
async function eventReceived(eventMessage, userProfile) {
async function eventReceived(eventMessage) {
/*
We expect here a JSON string with some or all of the following properties:
@@ -87,18 +91,7 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
} catch (err) {
let response = {
result: 'Error',
message: 'Client Interface eventMessage Not Correct JSON Format.'
}
return response
}
/*
At the Client Interface, events need to be emitted by the same userProfile that is
connected at the Network Node.
*/
if (eventReceived.emitterUserProfileId !== userProfile.userProfileId) {
let response = {
result: 'Error',
message: 'Client Interface emitterUserProfileId !== userProfileId Connected to Network Node.'
message: 'Peer Interface eventMessage Not Correct JSON Format.'
}
return response
}
@@ -119,7 +112,7 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
if (NT.projects.network.globals.memory.maps.EVENTS.get(eventReceived.eventId) !== undefined) {
let response = {
result: 'Error',
message: 'Client Interface Event Already Exists.'
message: 'Peer Interface Event Already Exists.'
}
return response
}
@@ -134,7 +127,7 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
let response = {
result: 'Ok',
message: 'Client Interface Event Processed.'
message: 'Peer Interface Event Processed.'
}
return response
@@ -144,94 +137,13 @@ exports.newSocialTradingModulesPeerInterface = function newSocialTradingModulesP
will be returned to the caller without doing anything else here.
*/
if (err.stack !== undefined) {
console.log('[ERROR] Client Interface -> err.stack = ' + err.stack)
console.log('[ERROR] Peer Interface -> err.stack = ' + err.stack)
}
let errorMessage = err.message
if (errorMessage === undefined) { errorMessage = err }
let response = {
result: 'Error',
message: 'Client Interface ' + errorMessage
}
return response
}
}
async function queryReceived(queryMessage, userProfile) {
/*
We expect here a JSON string with some or all of the following properties:
{
"queryType": 10,
"emitterUserProfileId": "a8de78f0-c3e4-4a2a-b7e8-f659073969db",
"targetUserProfileId": "a8de78f0-c3e4-4a2a-b7e8-f659073969db",
"emitterUserProfileHandle": "Luis-Fernando-Molina",
"targetUserProfileHandle": "Luis-Fernando-Molina",
"emitterBotProfileId": "a8de78f0-c3e4-4a2a-b7e8-f659073969db",
"targetBBotProfileId": "a8de78f0-c3e4-4a2a-b7e8-f659073969db",
"emitterPostHash": "a8de78f0-c3e4-4a2a-b7e8-f659073969db",
"targetPostHash": "a8de78f0-c3e4-4a2a-b7e8-f659073969db",
"timestamp": 124234234234,
"botAsset": "BTC",
"botExchange": "Binance",
"botEnabled": true,
"initialIndex": 35,
"amountRequested": 50,
"direction": "Past"
}
*/
let queryReceived
try {
queryReceived = JSON.parse(queryMessage)
} catch (err) {
let response = {
result: 'Error',
message: 'Client Interface queryMessage Not Correct JSON Format.'
}
return response
}
/*
At the Client Interface, queries need to be emitted by the same userProfile that is
connected at the Network Node.
*/
if (queryReceived.emitterUserProfileId !== userProfile.userProfileId) {
let response = {
result: 'Error',
message: 'Client Interface emitterUserProfileId !== userProfileId Connected to Network Node.'
}
return response
}
/*
Here we will process the query. This does not change the state of the Social Graph.
*/
try {
let query = NT.projects.socialTrading.modules.query.newSocialTradingModulesQuery()
query.initialize(queryReceived)
// console.log((new Date()).toISOString(), '- Client Interface', '- Query Message Received', queryMessage)
let response = {
result: 'Ok',
message: 'Client Interface Query Processed.',
data: query.execute()
}
// console.log((new Date()).toISOString(), '- Client Interface', '- Query Response Sent', JSON.stringify(response))
return response
} catch (err) {
/*
Any exception that happens while trying to execute the query.
*/
if (err.stack !== undefined) {
console.log('[ERROR] Client Interface -> err.stack = ' + err.stack)
}
let errorMessage = err.message
if (errorMessage === undefined) { errorMessage = err }
let response = {
result: 'Error',
message: 'Client Interface ' + errorMessage
message: 'Peer Interface ' + errorMessage
}
return response
}