Client Files into its own folder

This commit is contained in:
Luis Fernando Molina committed 2021-09-05 11:46:18 +02:00
1 parent 17656a12c0
commit 781f6b8fa1
84 files changed
+39 -40

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
exports.newCCXTServer = function newWebServer() {
const MODULE = "Web Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
}
+24
View File
@@ -0,0 +1,24 @@
exports.newDataFileServer = function newDataFileServer() {
const MODULE = "Data File Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
}
+236
View File
@@ -0,0 +1,236 @@
exports.newEventServer = function newEventServer() {
const MODULE = "Events Server"
const LOG_INFO = false
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run,
onMessage: onMessage
}
let eventHandlers = new Map()
let counter = 0
return thisObject
function finalize() {
}
function initialize() {
}
function onMessage(data, callbackFunction) {
try {
let command = JSON.parse(data)
switch (command.action) {
case "greetings": {
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "createEventHandler": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
/*
We will only create event handlers which were not created before. Remember that someone trying to listen events
at an event handler that does not exist, will create that eventhandler, so it is possible that the emitter
when trying to create the event handler in fact was late and the event handler is already there if the listener
arrived here first. An event handler created with this method is not destroyed if there are no listeners or they
all leave.
*/
eventHandler = newEventHandler()
eventHandler.deleteWhenAllListenersAreGone = false
eventHandlers.set(command.eventHandlerName, eventHandler)
}
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "deleteEventHandler": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler !== undefined) {
/*
We will only delete event handlers which have noone listening, allowing a listener to continue listening even
when the event emitter is gone, asuming that it could come back at some point in time and resume emitting.
*/
if (eventHandler.listeners.length === 0) {
eventHandlers.delete(command.eventHandlerName)
} else {
eventHandler.deleteWhenAllListenersAreGone = true
}
}
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "listenToEvent": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
/*
We will create event handlers which were not created before if a listener tries to listen to a handler that does not
exist before the emitter comes and create it. This is to aviod syncronization problems and also problems with emitters life
cycles with higher frecuency that the ones of listeners. Created in this way, event handlers are marked for deletion if
all listeners stop listening at one point in time.
*/
eventHandler = newEventHandler()
eventHandler.deleteWhenAllListenersAreGone = true
eventHandlers.set(command.eventHandlerName, eventHandler)
}
eventSubscriptionId = eventHandler.listenToEvent(command.eventHandlerName, command.eventType, command.callerId, handlerFunction, command.extraData)
function handlerFunction(event, extraData) {
let outputData = {
action: 'Event Raised',
eventHandlerName: command.eventHandlerName,
eventType: command.eventType,
event: event,
callerId: command.callerId,
extraData: extraData
}
callbackFunction(JSON.stringify(outputData))
}
let response = {
result: global.DEFAULT_OK_RESPONSE.result,
message: global.DEFAULT_OK_RESPONSE.message,
eventSubscriptionId: eventSubscriptionId
}
sendResponse(response)
return
}
case "stopListening": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
/* If the event handler does not exist anymore, then there is no need to perform further actiions. */
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
eventHandler.stopListening(command.eventHandlerName, command.eventType, command.callerId, command.eventSubscriptionId)
/*
We check here if there are no more listeners and the event handler original emmiter is also gone, then we need to delete
this event handlers since chances are that is not needed anymore.
*/
if (eventHandler.listeners.length === 0 && eventHandler.deleteWhenAllListenersAreGone === true) {
eventHandlers.delete(command.eventHandlerName)
}
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
case "raiseEvent": {
let eventHandler = eventHandlers.get(command.eventHandlerName)
if (eventHandler === undefined) {
eventHandler = newEventHandler()
eventHandlers.set(command.eventHandlerName, eventHandler)
/* No matter if it is the listener or the emiter the one that acts first, if an event handler does not exist we just create it acan keep it there. */
}
//console.log("[INFO] Client -> Events Server -> Raising Event " + command.eventHandlerName + " " + command.eventType)
eventHandler.raiseEvent(command.eventType, command.event)
sendResponse(global.DEFAULT_OK_RESPONSE)
return
}
}
console.log("[WARN] Client -> Events Server -> onMessage -> Unknown Command Received:" + data)
function sendResponse(message) {
if (command.callerId !== undefined) {
message.callerId = command.callerId
}
message.action = 'Event Server Response'
callbackFunction(JSON.stringify(message))
}
} catch (err) {
console.log("[ERROR] Client -> Events Server -> onMessage -> Bad Command Received:" + data)
console.log("[ERROR] Client -> Events Server -> onMessage -> An Error Happened:" + err.stack)
}
}
function run() {
}
function newEventHandler() {
let thisObject = {
name: undefined, // This is for debugging purposes only.
deleteWhenAllListenersAreGone: false,
listeners: [], // Here we store all the functions we will call when an event is raiseed.
listenToEvent: listenToEvent,
stopListening: stopListening,
raiseEvent: raiseEvent,
finalize: finalize
}
return thisObject
function finalize() {
thisObject.listeners = []
}
function listenToEvent(eventHandlerName, eventType, callerId, handler, extraData) {
let eventSubscriptionId = Math.trunc(Math.random() * 1000000)
/*
We can not allow to have the exact same listener more than once. In case that we find a listener trying to listen again, the first record will
be deleted and we are just going to consider the last one comming in.
*/
for (let i = 0; i < thisObject.listeners.length; i++) {
if (eventHandlerName === thisObject.listeners[i][0] && eventType === thisObject.listeners[i][1] && callerId === thisObject.listeners[i][2]) {
thisObject.listeners.splice(i, 1)
break
}
}
thisObject.listeners.push([eventHandlerName, eventType, callerId, handler, extraData, eventSubscriptionId])
return eventSubscriptionId
}
function stopListening(eventHandlerName, eventType, callerId, eventSubscriptionId) {
if (eventSubscriptionId !== undefined) {
for (let i = 0; i < thisObject.listeners.length; i++) {
if (eventSubscriptionId === thisObject.listeners[i][5]) {
thisObject.listeners.splice(i, 1)
return
}
}
}
if (eventHandlerName !== undefined && eventType !== undefined && callerId !== undefined) {
for (let i = 0; i < thisObject.listeners.length; i++) {
if (eventHandlerName === thisObject.listeners[i][0] && eventType === thisObject.listeners[i][1] && callerId === thisObject.listeners[i][2]) {
thisObject.listeners.splice(i, 1)
return
}
}
}
}
function raiseEvent(eventType, event) {
for (let i = 0; i < thisObject.listeners.length; i++) {
/* We will execute all the functions listening to this event type. */
if (thisObject.listeners[i][1] === eventType) {
let handler = thisObject.listeners[i][3]
let extraData = thisObject.listeners[i][4]
handler(event, extraData)
}
}
}
}
}
+725
View File
@@ -0,0 +1,725 @@
exports.newGithubServer = function newGithubServer() {
let thisObject = {
getGithubStars: getGithubStars,
getGithubWatchers: getGithubWatchers,
getGithubForks: getGithubForks,
mergePullRequests: mergePullRequests,
initialize: initialize,
finalize: finalize,
run: run
}
const GITHUB_API_WAITING_TIME = 250
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
async function getGithubStars(repository, username, token) {
return await getGithubUsernames('activity', 'listStargazersForRepo', repository, username, token)
}
async function getGithubWatchers(repository, username, token) {
return await getGithubUsernames('activity', 'listWatchersForRepo', repository, username, token)
}
async function getGithubForks(repository, username, token) {
return await getGithubUsernames('repos', 'listForks', repository, username, token)
}
async function mergePullRequests(commitMessage, username, token) {
return await mergeGithubPullRequests(commitMessage, username, token)
}
async function getGithubUsernames(endpoint, method, repository, username, token) {
try {
repository = unescape(repository)
username = unescape(username)
token = unescape(token)
let error
let githubListArray = []
return await getRepoInfo()
async function getRepoInfo() {
await doGithub()
if (error !== undefined) {
let docs = {
project: 'Governance',
category: 'Topic',
type: 'Gov Error - Get Repository Information',
anchor: undefined,
placeholder: {}
}
return respondWithDocsObject(docs, error)
}
return {
result: global.DEFAULT_OK_RESPONSE.result,
githubListArray: githubListArray
}
}
async function doGithub() {
const { Octokit } = require("@octokit/rest")
const octokit = new Octokit({
auth: token,
userAgent: 'Superalgos Beta 11'
})
await getList()
async function getList() {
const repo = repository
const owner = 'Superalgos'
const per_page = 100 // Max
let page = 0
let lastPage = false
while (lastPage === false) {
try {
page++
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit[endpoint][method]({
owner,
repo,
per_page,
page
});
if (listResponse.data.length < 100) {
lastPage = true
}
for (let i = 0; i < listResponse.data.length; i++) {
let listItem = listResponse.data[i]
let githubUsername
switch (endpoint) {
case 'activity': {
githubUsername = listItem.login
break
}
case 'repos': {
githubUsername = listItem.owner.login
break
}
}
//console.log(listItem)
githubListArray.push(githubUsername)
}
console.log('[INFO] Github Server -> getRepoInfo -> doGithub -> getList -> ' + method + ' Page = ' + page)
console.log('[INFO] Github Server -> getRepoInfo -> doGithub -> getList -> ' + method + ' Received = ' + listResponse.data.length)
} catch (err) {
console.log(err)
if (err.stack.indexOf('last page') >= 0) {
return
} else {
console.log('[ERROR] Github Server -> getRepoInfo -> doGithub -> getList ->Method call produced an error.')
console.log('[ERROR] Github Server -> getRepoInfo -> doGithub -> getList ->err.stack = ' + err.stack)
console.log('[ERROR] Github Server -> getRepoInfo -> doGithub -> getList ->repository = ' + repository)
console.log('[ERROR] Github Server -> getRepoInfo -> doGithub -> getList ->username = ' + username)
console.log('[ERROR] Github Server -> getRepoInfo -> doGithub -> getList ->token starts with = ' + token.substring(0, 10) + '...')
console.log('[ERROR] Github Server -> getRepoInfo -> doGithub -> getList ->token ends with = ' + '...' + token.substring(token.length - 10))
error = err
return
}
}
}
}
}
} catch (err) {
console.log('[ERROR] Github Server -> getRepoInfo -> Method call produced an error.')
console.log('[ERROR] Github Server -> getRepoInfo -> err.stack = ' + err.stack)
console.log('[ERROR] Github Server -> getRepoInfo -> repository = ' + repository)
console.log('[ERROR] Github Server -> getRepoInfo -> username = ' + username)
console.log('[ERROR] Github Server -> getRepoInfo -> token starts with = ' + token.substring(0, 10) + '...')
console.log('[ERROR] Github Server -> getRepoInfo -> token ends with = ' + '...' + token.substring(token.length - 10))
let error = {
result: 'Fail Because',
message: err.message,
stack: err.stack
}
return error
}
}
async function mergeGithubPullRequests(commitMessage, username, token) {
try {
commitMessage = unescape(commitMessage)
username = unescape(username)
token = unescape(token)
const repository = 'Superalgos'
/* Unsavping # */
for (let i = 0; i < 10; i++) {
commitMessage = commitMessage.replace('_SLASH_', '/')
commitMessage = commitMessage.replace('_HASHTAG_', '#')
}
let error
let githubPrListArray = []
return await processOpenPullRequests()
async function processOpenPullRequests() {
await doGithub()
if (error !== undefined) {
let docs = {
project: 'Governance',
category: 'Topic',
type: 'Gov Error - Pull Requests Not Processed',
anchor: undefined,
placeholder: {}
}
return respondWithDocsObject(docs, error)
}
return {
result: global.DEFAULT_OK_RESPONSE.result
}
}
async function doGithub() {
try {
const repo = repository
const owner = 'Superalgos'
const { Octokit } = require("@octokit/rest")
const octokit = new Octokit({
auth: token,
userAgent: 'Superalgos Beta 11'
})
await getPrList()
await mergePrs()
await closePrsToMaster()
async function getPrList() {
const per_page = 100 // Max
let page = 0
let lastPage = false
while (lastPage === false) {
try {
page++
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit.rest.pulls.list({
owner: owner,
repo: repo,
state: 'open',
head: 'develop',
base: 'develop',
sort: undefined,
direction: undefined,
per_page: per_page,
page: page
});
if (listResponse.data.length < 100) {
lastPage = true
}
console.log('[INFO] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList -> Receiving Page = ' + page)
for (let i = 0; i < listResponse.data.length; i++) {
let pullRequest = listResponse.data[i]
console.log('[INFO] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList -> Pull Request "' + pullRequest.title + '" found and added to the list to validate. ')
githubPrListArray.push(pullRequest)
}
console.log('[INFO] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList -> Received = ' + listResponse.data.length)
} catch (err) {
console.log(err)
if (err.stack.indexOf('last page') >= 0) {
return
} else {
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->Method call produced an error.')
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->err.stack = ' + err.stack)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->repository = ' + repository)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->username = ' + username)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->token starts with = ' + token.substring(0, 10) + '...')
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> getPrList ->token ends with = ' + '...' + token.substring(token.length - 10))
error = err
return
}
}
}
}
async function mergePrs() {
/*
In order to automatically merge a PRs we will run several validations first.
We want to automate specifically the merging of Profile File changes at the
Governance System done by the same Github user name that matches the profile
changed. We will also not do the merge if there are more than one file at the
PR.
We will go through the list of open PRs and run the validations at each one of them.
*/
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Ready to Validate ' + githubPrListArray.length + ' pull requests. ')
for (let i = 0; i < githubPrListArray.length; i++) {
let pullRequest = githubPrListArray[i]
/*
Lets get the files changed at this Pull Request.
*/
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit.rest.pulls.listFiles({
owner: owner,
repo: repo,
pull_number: pullRequest.number
});
let filesChanged = listResponse.data
let fileContentUrl // URL to the only file at the PR
let fileContent // File content of the only file at the PR
let userProfile // User Profile Object
let githubUsername // The Github user name of who is submitting the Pull Request
let mergeResponse // The response received from the call to Gihub to merge the Pull Request
if (await validatePrHasMoreThanOneFile() === false) { continue }
if (await validateFileNameEqualsGithubUsername() === false) { continue }
if (await validateFileChangedIsUserProfile() === false) { continue }
if (await validateMessageSignedIsGithubUsername() === false) { continue }
if (await validateUserProfileNodeNameEqualsGithubUsername() === false) { continue }
if (await validateUserProfileIdDoesNotBelongtoAnotherUserProfile() === false) { continue }
if (await validateUserProfileBlockchainAccountDoesNotBelongtoAnotherUserProfile() === false) { continue }
if (await mergePullRequest() === false) {
console.log('[WARN] Github Server -> mergeGithubPullRequests -> Merge Failed -> Pull Request "' + pullRequest.title + '" not merged because Github could not merge it. -> mergeResponse.message = ' + mergeResponse.data.message)
} else {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Merge Succed -> Pull Request "' + pullRequest.title + '" successfully merged. -> mergeResponse.message = ' + mergeResponse.data.message)
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request was automatically merged by the Superalgos Governance System because it was detected that the Github User " ' + githubUsername + '" who submitted it, modified its own User Profile Plugin File and nothning else but that file. All validations were successfull.'
});
}
async function validatePrHasMoreThanOneFile() {
/*
Validation #1: If the PR has more than one file, then we will not automatically
merge it.
*/
if (filesChanged.length !== 1) {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #1 Failed -> Pull Request "' + pullRequest.title + '" not merged because it contains more than 1 file. -> fileCount = ' + filesChanged.length)
/*
We will close PRs that contains any User Profile file together with other files in the same Pull Request.
This will avoid manual merges to include User Profile files.
*/
for (let j = 0; j < filesChanged.length; j++) {
let pullRequestFile = filesChanged[j]
let fileContentUrl = pullRequestFile.raw_url
if (fileContentUrl.indexOf('Governance/Plugins/User-Profiles') >= 0) {
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that a User Profile file... \n\n' + fileContentUrl + '\n\n...was submitted together with ' + (filesChanged.length - 1) + ' other file/s. User Profiles files as per the Governance System rules, must be the only file present at a Pull Request in order to pass all the validations and be automatically merged.'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
break
}
}
return false
}
}
async function validateFileNameEqualsGithubUsername() {
/*
Validation #2: File Name must be the same to the Github Username of the PR owner.
*/
let pullRequestFile = filesChanged[0]
fileContentUrl = pullRequestFile.raw_url
if (fileContentUrl.indexOf('Governance/Plugins/User-Profiles') < 0) {
/*
If it is not a user profile then there is no need to auto merge.
*/
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #2 Failed -> Pull Request "' + pullRequest.title + '" not merged because the file modified at the Pull Request is not a User Profile file. -> fileContentUrl = ' + fileContentUrl)
return false
}
let splittedURL = fileContentUrl.split('/')
let fileName = splittedURL[splittedURL.length - 1]
let splittedFileName = fileName.split('.')
fileName = splittedFileName[0]
githubUsername = pullRequest.user.login
if (githubUsername !== fileName) {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #2 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Github Username is not equal to the File Name. -> Github Username = ' + githubUsername + '-> fileName = ' + fileName)
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that the Github User "' + githubUsername + '" who submitted it, is not equal to the name of the User Profile Plugin File.\n\n File Name = "' + fileName + '"'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateFileChangedIsUserProfile() {
/*
Validation #3: The file changed at the PR is a User Profile.
*/
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
fileContent = await CL.projects.foundations.utilities.webAccess.fetchAPIDataFile(fileContentUrl)
userProfile = JSON.parse(fileContent)
if (userProfile.type !== 'User Profile') {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #3 Failed -> Pull Request "' + pullRequest.title + '" not merged because the file modified is not a User Profile. -> Type = ' + userProfile.type)
return false
}
}
async function validateMessageSignedIsGithubUsername() {
/*
Validation #4: The message signed at the config is not the Github Username.
*/
let config = JSON.parse(userProfile.config)
let messageSigned = config.signature.message
if (messageSigned !== githubUsername) {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #4 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Github Username is not equal to the Message Signed at the User Profile. -> Github Username = ' + githubUsername + '-> messageSigned = ' + messageSigned)
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that the Github User "' + githubUsername + '" who submitted it, is not equal to the Message Signed at the User Profile.\n\n Message Signed = "' + messageSigned + '"'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateUserProfileNodeNameEqualsGithubUsername() {
/*
Validation #5: The name of the User Profile node is not the Github Username.
*/
if (userProfile.name !== githubUsername) {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #5 Failed -> Pull Request "' + pullRequest.title + '" not merged because the Github Username is not equal to the User Profile node\'s name. -> Github Username = ' + githubUsername + '-> userProfile.name = ' + userProfile.name)
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because it was detected that the Github User "' + githubUsername + '" who submitted it, is not equal to the User Profile node\'s name.\n\n User Profile Name = "' + userProfile.name + '"'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateUserProfileIdDoesNotBelongtoAnotherUserProfile() {
/*
Validation #6: The id of the User Profile can not be the id of an already existing User Profile
unless the existing one belongs to the same Github username.
*/
let userProfileIdMap = new Map()
let pluginFileNames = await SA.projects.foundations.utilities.plugins.getPluginFileNames(
'Governance',
'User-Profiles'
)
for (let i = 0; i < pluginFileNames.length; i++) {
let pluginFileName = pluginFileNames[i]
let pluginFileContent = await SA.projects.foundations.utilities.plugins.getPluginFileContent(
'Governance',
'User-Profiles',
pluginFileName
)
let otherUserProfile = JSON.parse(pluginFileContent)
userProfileIdMap.set(otherUserProfile.id, otherUserProfile.name)
}
let testUserProfile = userProfileIdMap.get(userProfile.id)
if (testUserProfile === undefined) { return true }
if (testUserProfile !== userProfile.name) {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #6 Failed -> Pull Request "' + pullRequest.title + '" not merged because the User Profile Id already exists and belongs to another User Profile on record. -> Profile Id = ' + userProfile.id + '-> User Profile with the same Id = ' + testUserProfile)
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the User Profile Id already exists and belongs to another User Profile on record. \n\nUser Profile Id = "' + userProfile.id + '" \n\n User Profile with the same Id = "' + testUserProfile + '"'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
}
async function validateUserProfileBlockchainAccountDoesNotBelongtoAnotherUserProfile() {
try {
/*
Validation #7 The blockchain account of the User Profile can not be the
blockchain account of an already existing User Profile
unless the existing one belongs to the same Github username.
*/
let userProfileIdMap = new Map()
let pluginFileNames = await SA.projects.foundations.utilities.plugins.getPluginFileNames(
'Governance',
'User-Profiles'
)
for (let i = 0; i < pluginFileNames.length; i++) {
let pluginFileName = pluginFileNames[i]
let pluginFileContent = await SA.projects.foundations.utilities.plugins.getPluginFileContent(
'Governance',
'User-Profiles',
pluginFileName
)
let otherUserProfile = JSON.parse(pluginFileContent)
let config = JSON.parse(otherUserProfile.config)
let messageSigned = JSON.stringify(config.signature)
let serverResponse = await CL.servers.WEB3_SERVER.recoverAddress(
messageSigned
)
userProfileIdMap.set(serverResponse.address, otherUserProfile.name)
}
let config = JSON.parse(userProfile.config)
let messageSigned = JSON.stringify(config.signature)
let serverResponse = await CL.servers.WEB3_SERVER.recoverAddress(
messageSigned
)
let testUserProfile = userProfileIdMap.get(serverResponse.address)
if (testUserProfile === undefined) { return true }
if (testUserProfile !== userProfile.name) {
console.log('[INFO] Github Server -> mergeGithubPullRequests -> Validation #7 Failed -> Pull Request "' + pullRequest.title + '" not merged because the User Profile Blockchain Account already exists and belongs to another User Profile on record. -> Profile Blockchain Account = ' + serverResponse.address + '-> User Profile with the same Blockchain Account = ' + testUserProfile)
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'This Pull Request could not be automatically merged and was closed by the Superalgos Governance System because the User Profile Blockchain Account already exists and belongs to another User Profile on record. \n\nUser Profile Blockchain Account = "' + serverResponse.address + '" \n\n User Profile with the same Blockchain Account = "' + testUserProfile + '"'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
return false
}
} catch (err) {
console.log(err.stack)
}
}
async function mergePullRequest() {
/*
All validations passed, we will proceed an merge this Pull Request.
*/
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
mergeResponse = await octokit.rest.pulls.merge({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
commit_title: 'Changes in User Profile done by Profile Owner ' + githubUsername + ' automatically merged by Superalgos.'
});
return mergeResponse.data.merged
}
}
}
async function closePrsToMaster() {
let githubPrListMaster = []
const per_page = 100 // Max
let page = 0
try {
page++
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
let listResponse = await octokit.rest.pulls.list({
owner: owner,
repo: repo,
state: 'open',
head: undefined,
base: 'master',
sort: undefined,
direction: undefined,
per_page: per_page,
page: page
});
if (listResponse.data.length < 100) {
lastPage = true
}
console.log('[INFO] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster -> Receiving Page = ' + page)
for (let i = 0; i < listResponse.data.length; i++) {
let pullRequest = listResponse.data[i]
console.log('[INFO] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster -> Pull Request "' + pullRequest.title + '" found and added to the list to validate. ')
githubPrListMaster.push(pullRequest)
}
console.log('[INFO] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster -> Received = ' + listResponse.data.length)
for (let i = 0; i < githubPrListMaster.length; i++) {
let pullRequest = githubPrListMaster[i]
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.issues.createComment({
owner: owner,
repo: repo,
issue_number: pullRequest.number,
body: 'Hi, this is the Superalgos Governance System taking notice that you have submitted a pull request directly to the master branch.\n\nThanks for submitting a PR to the Superalgos Project. We value every contribution and everyone is welcome to send PRs. Unfortunatelly we are not merging pull requests directly into the master branch. Consider resubmitting to the develop branch intstead. For your convinienve, you can swithch branches from within the app, at the footer of the Docs tab. \n\n I will close this pull request now and look forward for your next contribution either to the develop branch or any other branch available for this purpose.'
});
await CL.projects.foundations.utilities.asyncFunctions.sleep(GITHUB_API_WAITING_TIME)
await octokit.rest.pulls.update({
owner: owner,
repo: repo,
pull_number: pullRequest.number,
state: 'closed'
});
}
} catch (err) {
console.log(err)
if (err.stack.indexOf('last page') >= 0) {
return
} else {
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->Method call produced an error.')
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->err.stack = ' + err.stack)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->repository = ' + repository)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->username = ' + username)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->token starts with = ' + token.substring(0, 10) + '...')
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> closePrsToMaster ->token ends with = ' + '...' + token.substring(token.length - 10))
error = err
return
}
}
}
} catch (err) {
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> doGithub -> err.stack = ' + err.stack)
}
}
} catch (err) {
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> Method call produced an error.')
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> err.stack = ' + err.stack)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> repository = ' + repository)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> username = ' + username)
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> token starts with = ' + token.substring(0, 10) + '...')
console.log('[ERROR] Github Server -> mergeGithubPullRequests -> token ends with = ' + '...' + token.substring(token.length - 10))
let error = {
result: 'Fail Because',
message: err.message,
stack: err.stack
}
return error
}
}
function respondWithDocsObject(docs, error) {
if (error.message !== undefined) {
docs.placeholder.errorMessage = {
style: 'Error',
text: error.message
}
}
if (error.stack !== undefined) {
docs.placeholder.errorStack = {
style: 'Javascript',
text: error.stack
}
}
if (error.code !== undefined) {
docs.placeholder.errorCode = {
style: 'Json',
text: error.code
}
}
docs.placeholder.errorDetails = {
style: 'Json',
text: JSON.stringify(error, undefined, 4)
}
let customResponse = {
result: global.CUSTOM_FAIL_RESPONSE.result,
docs: docs
}
return customResponse
}
}
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
exports.newPluginServer = function newPluginServer() {
const MODULE = "Plugin Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
}
+24
View File
@@ -0,0 +1,24 @@
exports.newProjectFileServer = function newProjectFileServer() {
const MODULE = "Project File Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
}
+328
View File
@@ -0,0 +1,328 @@
exports.newTaskManagerServer = function newTaskManagerServer() {
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
/*
This server creates and destroys Task Servers according to what is going on at the UI. Each of these created servers will do their own
work. The responsibility of this server is to manage those children processes in order to be in sync with what the end user want and is defining
at the user interface.
*/
const { fork } = require('child_process')
tasksMap = new Map()
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
/*
Here we will create an Event Handler for this server. After that we will listen to events happening here. Elements of the UI will raise events here,
as a way to communicate what is going on with the user interacting with UI components. That is the way this server will know for example when a new
task needs to be created or destroyed.
*/
let eventsServerClient = newEventsServerClient()
eventsServerClient.createEventHandler('Task Manager')
eventsServerClient.listenToEvent('Task Manager', 'Run Task', undefined, undefined, undefined, runTask)
eventsServerClient.listenToEvent('Task Manager', 'Stop Task', undefined, undefined, undefined, stopTask)
eventsServerClient.listenToEvent('Task Manager', 'Task Status', undefined, undefined, undefined, taskStatus)
function runTask(message) {
//console.log('[INFO] Client -> Task Manager Server -> runTask -> Entering function.')
if (message.event === undefined) {
console.log('[WARN] Client -> Task Manager Server -> runTask -> Message Received Without Event -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
if (message.event.taskId === undefined) {
console.log('[WARN] Client -> Task Manager Server -> runTask -> Message Received Without taskId -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
if (message.event.taskDefinition === undefined) {
console.log('[WARN] Client -> Task Manager Server -> runTask -> Message Received Without taskDefinition -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
if (tasksMap.get(message.event.taskId) !== undefined) {
let key = message.event.taskName + '-' + 'Task' + '-' + message.event.taskId
eventsServerClient.raiseEvent(key, 'Running') // Meaning Task Running
return
}
//console.log('[INFO] Client -> Task Manager Server -> runTask -> Task Name = ' + message.event.taskName)
//console.log('[INFO] Client -> Task Manager Server -> runTask -> Task Id = ' + message.event.taskId)
let path = global.env.PATH_TO_TASK_SERVER + '/Task.js'
/* Workarround to avoid having the same debug port at the forked process which makes it crash. */
for (let i = 0; i < process.execArgv.length; i++) {
let argument = process.execArgv[i]
if (argument.indexOf('--inspect') > -1) {
process.execArgv[i] = ''
}
}
/*
Forking this process:
The Task Server is going to run at a fork of this process. In this way we have a some communication capabilities
between processes, which is kind of limited but good enough for what we need. We send to the forked process
the taskId and taskName at the same time we create the process. Once the process is up and running it will
emit an event that is ready, and at that point we will send all the information needed to run the task.
*/
let task = {
childProcess: fork(path, [message.event.taskId], { stdio: 'inherit' }),
id: message.event.taskId,
name: message.event.taskName
}
/* Remember this is a running task now */
tasksMap.set(message.event.taskId, task)
/* If the Task Server crashes, we remove it from our task map */
task.childProcess.on('error', (err) => {
console.log('[ERROR] Client -> Task Manager Server -> runTask -> Problem with Task Name = ' + task.name)
console.log('[ERROR] Client -> Task Manager Server -> runTask -> Problem with Task Id = ' + task.id)
console.log(`[ERROR] Client -> Task Manager Server -> runTask -> Task Server exited with error ${err}`)
tasksMap.delete(task.id)
})
/* If the Tast Server stops, we remove it from our task map */
task.childProcess.on('close', (code, signal) => {
//console.log('[INFO] Client -> Task Manager Server -> runTask -> Task Terminated. -> Task Name = ' + task.name)
//console.log('[INFO] Client -> Task Manager Server -> runTask -> Task Terminated. -> Task Id = ' + task.id)
tasksMap.delete(task.id)
})
/*
We listen to the newly created Task Server events, waiting until it is up and ready to receive all the Task specific
instruction, to know what kind of task to execute.
*/
eventsServerClient.listenToEvent('Task Manager - ' + message.event.taskId, 'Nodejs Process Ready for Task', undefined, undefined, undefined, sendStartingEvent)
/*
Here we do send the rest of the task information we have, which is what defines what the Task Server is actually
going to do. From there on, here at the Task Manager, we have nothing to do until either the Task Server crashes or exit,
or the end users requests to stop it. Note that the due to the size of the instructions can not be sent via
intra-process communications.
*/
function sendStartingEvent() {
//console.log('[INFO] Client -> Task Manager Server -> runTask -> Emitting Event -> key = ' + 'Task Server - ' + task.id)
eventsServerClient.raiseEvent('Task Server - ' + task.id, 'Run Task', message.event)
}
}
function stopTask(message) {
//console.log('[INFO] Client -> Task Manager Server -> stopTask -> Entering function.')
if (message.event === undefined) {
console.log('[WARN] Client -> Task Manager Server -> stopTask -> Message Received Without Event -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
if (message.event.taskId === undefined) {
console.log('[WARN] Client -> Task Manager Server -> stopTask -> Message Received Without taskId -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
//console.log('[INFO] Client -> Task Manager Server -> stopTask -> Task Name = ' + message.event.taskName)
//console.log('[INFO] Client -> Task Manager Server -> stopTask -> Task Id = ' + message.event.taskId)
let task = tasksMap.get(message.event.taskId)
/*
The instruction to stop the Task Server process is sent via intra-process messaging. We will remove this task from
our map once we received the onClose event of our forked process.
*/
if (task) {
task.childProcess.send('Stop this Task');
//console.log('[INFO] Client -> Task Manager Server -> stopTask -> Child Process instructed to finish.')
} else {
console.log('[WARN] Client -> Task Manager Server -> stopTask -> Cannot delete Task that does not exist.')
}
}
function taskStatus(message) {
//console.log('[INFO] Client -> Task Manager Server -> taskStatus -> Entering function.')
if (message.event === undefined) {
console.log('[WARN] Client -> Task Manager Server -> taskStatus -> Message Received Without Event -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
if (message.event.taskId === undefined) {
console.log('[WARN] Client -> Task Manager Server -> taskStatus -> Message Received Without taskId -> message = ' + JSON.stringify(message).substring(0, 1000))
return
}
//console.log('[INFO] Client -> Task Manager Server -> taskStatus -> Task Name = ' + message.event.taskName)
//console.log('[INFO] Client -> Task Manager Server -> taskStatus -> Task Id = ' + message.event.taskId)
let task = tasksMap.get(message.event.taskId)
let event = {}
if (task) {
event.status = 'Task Process Running'
eventsServerClient.raiseEvent('Task Client - ' + message.event.taskId, 'Task Status', event)
} else {
event.status = 'Task Process Not Running'
eventsServerClient.raiseEvent('Task Client - ' + message.event.taskId, 'Task Status', event)
}
}
}
function newEventsServerClient() {
let thisObject = {
initialize: initialize,
finalize: finalize,
createEventHandler: createEventHandler,
deleteEventHandler: deleteEventHandler,
listenToEvent: listenToEvent,
stopListening: stopListening,
raiseEvent: raiseEvent,
onMessage: onMessage
}
let eventListeners = new Map()
let responseWaiters = new Map()
return thisObject
function finalize() {
/* Before disconnecting we will forze all eventListeners to stop listening. */
const eventListenersArray = [...eventListeners.values()]
for (let i = 0; i < eventListenersArray.length; i++) {
let handler = eventListenersArray[i]
let eventCommand = {
action: 'stopListening',
eventHandlerName: handler.eventHandlerName,
eventType: handler.eventType,
callerId: handler.callerId
}
sendCommand(eventCommand)
}
}
function initialize() {
}
function onMessage(data) {
try {
let message = JSON.parse(data)
if (message.action === 'Event Raised') {
let key
if (message.callerId) {
key = message.eventHandlerName + '-' + message.eventType + '-' + message.callerId
} else {
key = message.eventHandlerName + '-' + message.eventType
}
let handler = eventListeners.get(key)
if (handler) {
handler.callBack(message)
} else {
console.log(key + ' not found so could not deliver event raised.')
console.log(' Message = ' + data)
}
return
}
if (message.action === 'Event Server Response') {
let handler = responseWaiters.get(message.callerId)
if (handler) {
handler(message)
}
return
}
} catch (err) {
console.log('[ERROR] Client -> Task Manager Server -> onMessage -> Error Receiving Message from Events Server -> data = ' + JSON.stringify(data))
console.log('[ERROR] Client -> Task Manager Server -> onMessage -> Error Receiving Message from Events Server -> error = ' + err.stack)
}
}
function sendCommand(command, responseCallBack, eventsCallBack) {
try {
if (command.action === 'listenToEvent') {
let key
if (command.callerId) {
key = command.eventHandlerName + '-' + command.eventType + '-' + command.callerId
} else {
key = command.eventHandlerName + '-' + command.eventType
}
let handler = {
eventHandlerName: command.eventHandlerName,
eventType: command.eventType,
callerId: command.callerId,
callBack: eventsCallBack
}
eventListeners.set(key, handler)
}
if (command.callerId && responseCallBack) {
responseWaiters.set(command.callerId, responseCallBack)
}
CL.servers.EVENT_SERVER.onMessage(JSON.stringify(command), thisObject.onMessage)
} catch (err) {
console.log('[ERROR] Client -> Task Manager Server -> sendCommand -> Error Sending Command to Events Server -> command = ' + JSON.stringify(command))
console.log('[ERROR] Client -> Task Manager Server -> sendCommand -> Error Sending Command to Events Server -> error = ' + err.stack)
}
}
function createEventHandler(eventHandlerName, callerId, responseCallBack) {
let eventCommand = {
action: 'createEventHandler',
eventHandlerName: eventHandlerName,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
function deleteEventHandler(eventHandlerName, callerId, responseCallBack) {
let eventCommand = {
action: 'deleteEventHandler',
eventHandlerName: eventHandlerName,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
function listenToEvent(eventHandlerName, eventType, extraData, callerId, responseCallBack, eventsCallBack) {
let eventCommand = {
action: 'listenToEvent',
eventHandlerName: eventHandlerName,
eventType: eventType,
extraData: extraData,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack, eventsCallBack)
}
function stopListening(eventHandlerName, eventType, eventSubscriptionId, callerId, responseCallBack) {
/* User either needs to specify a valid eventSubscriptionId OR the 3 params: eventHandlerName, eventType, callerId which were used when start listening to events. */
let eventCommand = {
action: 'stopListening',
eventHandlerName: eventHandlerName,
eventType: eventType,
eventSubscriptionId: eventSubscriptionId,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
function raiseEvent(eventHandlerName, eventType, event, callerId, responseCallBack) {
let eventCommand = {
action: 'raiseEvent',
eventHandlerName: eventHandlerName,
eventType: eventType,
event: event,
callerId: callerId
}
sendCommand(eventCommand, responseCallBack)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
exports.newUIFileServer = function newUIFileServer() {
const MODULE = "UI File Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
}
+343
View File
@@ -0,0 +1,343 @@
exports.newWeb3Server = function newWeb3Server() {
const MODULE = "Web3 Server"
let thisObject = {
getNetworkClientStatus: getNetworkClientStatus,
createWalletAccount: createWalletAccount,
getWalletBalances: getWalletBalances,
signData: signData,
recoverAddress: recoverAddress,
mnemonicToPrivateKey: mnemonicToPrivateKey,
payContributors: payContributors,
initialize: initialize,
finalize: finalize,
run: run
}
const Web3 = require('web3');
let web3Map = new Map()
return thisObject
function finalize() {
web3Map = undefined
}
function initialize() {
}
function run() {
}
async function getNetworkClientStatus(host, port, interface) {
let key = 'host (' + host + ') at port (' + port + ') via interface (' + interface + ')'
try {
let web3 = web3Map.get(key)
if (web3 === undefined) {
/* This means that we never got connected to this client before */
let web3 = await connectToClient(key, host, port, interface)
if (web3.error !== undefined) {
return web3
}
return await returnStatus(web3)
} else {
return await returnStatus(web3)
}
async function returnStatus(web3) {
let status = {}
status.isSyncing = await web3.eth.isSyncing()
status.chainId = await web3.eth.getChainId()
status.currentBlockNumber = await web3.eth.getBlockNumber()
status.result = 'Ok'
return status
}
} catch (err) {
return { error: 'Could not connect to ' + key + '. ' + err.stack + '.' }
}
}
async function createWalletAccount(entropy) {
try {
let web3 = new Web3()
let account = web3.eth.accounts.create()
return {
address: account.address,
privateKey: account.privateKey,
result: 'Ok'
}
} catch (err) {
return { error: 'Could not create the account. ' + err.stack }
}
}
async function getWalletBalances(host, port, interface, walletDefinition) {
let key = 'host (' + host + ') at port (' + port + ') via interface (' + interface + ')'
try {
let web3 = web3Map.get(key)
if (web3 === undefined) {
/* This means that we never got connected to this client before */
let web3 = await connectToClient(key, host, port, interface)
if (web3.error !== undefined) {
return web3
}
return await returnAccountBalances(web3)
} else {
return await returnAccountBalances(web3)
}
async function returnAccountBalances(web3) {
let responseData = {}
for (let i = 0; i < walletDefinition.walletAccounts.length; i++) {
let walletAccount = walletDefinition.walletAccounts[i]
if (walletAccount.ethBalance !== undefined) {
try {
walletAccount.ethBalance.value = await web3.eth.getBalance(walletAccount.config.address)
} catch (err) {
if (err.message.indexOf('Provided address') >= 0) {
walletAccount.error = 'Invalid configured address.'
} else {
walletAccount.error = err.message
}
}
}
for (let j = 0; j < walletAccount.tokenBalances.length; j++) {
let tokenBalance = walletAccount.tokenBalances[j]
if (tokenBalance.referenceParent === undefined) { continue }
if (tokenBalance.referenceParent.parentNode === undefined) { continue }
if (tokenBalance.referenceParent.smartContracts === undefined) { continue }
if (tokenBalance.referenceParent.config.codeName === undefined) {
tokenBalance.error = 'Reference Parent without config.codeName defined.'
continue
}
if (tokenBalance.referenceParent.smartContracts.config.address === undefined) {
tokenBalance.error = 'Reference Parent Smart Contract without config.address defined.'
continue
}
let tokenContractAddress = tokenBalance.referenceParent.smartContracts.config.address
// The minimum ABI to get ERC20 Token balance
let minABI = [
// balanceOf
{
"constant": true,
"inputs": [{ "name": "_owner", "type": "address" }],
"name": "balanceOf",
"outputs": [{ "name": "balance", "type": "uint256" }],
"type": "function"
},
// decimals
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [{ "name": "", "type": "uint8" }],
"type": "function"
}
];
let contract = new web3.eth.Contract(minABI, tokenContractAddress);
try {
tokenBalance.value = await contract.methods.balanceOf(walletAccount.config.address).call()
} catch (err) {
if (err.message.indexOf('Provided address') >= 0) {
walletAccount.error = 'Invalid configured address.'
} else {
walletAccount.error = err.message
}
}
}
}
responseData.result = 'Ok'
responseData.walletDefinition = walletDefinition
return responseData
}
} catch (err) {
return { error: 'Could not connect to ' + key + '. ' + err.stack + '.' }
}
}
async function connectToClient(key, host, port, interface) {
let web3
switch (interface) {
case 'ws': {
web3 = new Web3('ws://' + host + ':' + port + '');
break
}
case 'http': {
web3 = new Web3('http://' + host + ':' + port + '');
break
}
default: {
return { error: 'Interface parameter must be either ws or http. Received ' + interface }
}
}
return await testConnection()
async function testConnection() {
let accounts = await web3.eth.getAccounts()
if (web3.currentProvider.connected === false) {
return { error: 'Connection to ' + key + ' could not be established.' }
} else {
web3Map.set(key, web3)
return web3
}
}
}
async function signData(privateKey, data) {
try {
let web3 = new Web3()
let signature = web3.eth.accounts.sign(data, privateKey)
return {
signature: signature,
result: 'Ok'
}
} catch (err) {
return { error: 'Could not sign the data. ' + err.stack }
}
}
async function recoverAddress(signature) {
try {
let signatureObject = JSON.parse(signature)
let web3 = new Web3()
let address = web3.eth.accounts.recover(signatureObject)
return {
address: address,
result: 'Ok'
}
} catch (err) {
return { error: 'Could not recover address. ' + err.stack }
}
}
async function mnemonicToPrivateKey(mnemonic) {
try {
const ethers = require('ethers')
let wallet = ethers.Wallet.fromMnemonic(mnemonic)
if (wallet.privateKey !== undefined) {
return {
address: wallet.address,
privateKey: wallet.privateKey,
result: 'Ok'
}
} else {
return {
address: undefined,
privateKey: undefined,
result: 'Fail'
}
}
} catch (err) {
return { error: 'Could not convert to Private Key. ' + err.stack }
}
}
async function payContributors(contractAddress, contractAbi, paymentsArray, mnemonic) {
try {
let response = await mnemonicToPrivateKey(mnemonic)
let privateKey = response.privateKey
for (let i = 0; i < paymentsArray.length; i++) {
await CL.projects.foundations.utilities.asyncFunctions.sleep(10000)
let payment = paymentsArray[i]
sendTokens(
i + 1,
payment.userProfile,
payment.from,
payment.to,
payment.amount
)
}
async function sendTokens(number, userProfile, fromAddress, toAddress, tokenAmount) {
try {
console.log('')
console.log('---------------------------------------------------------------------------------------------------------------------------------------------------')
console.log(' Payment # ' + number + ' - User Profile: ' + userProfile + ' - SA Tokens Amount: ' + tokenAmount / 1000000000000000000 + ' - Address: ' + toAddress)
console.log('---------------------------------------------------------------------------------------------------------------------------------------------------')
console.log('')
const Tx = require('ethereumjs-tx').Transaction;
const web3 = new Web3(new Web3.providers.HttpProvider('https://bsc-dataseed.binance.org/'))
const amount = web3.utils.toHex(tokenAmount)
privateKey = privateKey.replace('0x', '')
const privateKeyBuffer = Buffer.from(privateKey, 'hex')
const contractAbiObject = JSON.parse(contractAbi)
const contract = new web3.eth.Contract(contractAbiObject, contractAddress, { from: fromAddress })
const Common = require('ethereumjs-common').default
const BSC_FORK = Common.forCustomChain(
'mainnet',
{
name: 'Binance Smart Chain Mainnet',
networkId: 56,
chainId: 56,
url: 'https://bsc-dataseed.binance.org/'
},
'istanbul',
);
const nonce = await web3.eth.getTransactionCount(fromAddress);
const rawTransaction = {
"from": fromAddress,
"gasPrice": web3.utils.toHex(5000000000),
"gasLimit": web3.utils.toHex(210000),
"to": contractAddress, "value": "0x0",
"data": contract.methods.transfer(toAddress, amount).encodeABI(),
"nonce": web3.utils.toHex(nonce)
};
const transaction = new Tx(rawTransaction, { 'common': BSC_FORK })
transaction.sign(privateKeyBuffer)
console.log('Transaction:', rawTransaction)
const result = await web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
console.log('Result:', result)
return result
} catch (err) {
console.log('[ERROR] web3Server -> sendTokens -> err.stack = ' + err.stack)
}
}
return {
address: wallet.address,
privateKey: wallet.privateKey,
result: 'Ok'
}
} catch (err) {
return { error: 'Could not convert to Private Key. ' + err.stack }
}
}
}
+24
View File
@@ -0,0 +1,24 @@
exports.newWebServer = function newWebServer() {
const MODULE = "Web Server"
let thisObject = {
initialize: initialize,
finalize: finalize,
run: run
}
return thisObject
function finalize() {
}
function initialize() {
}
function run() {
}
}
+103
View File
@@ -0,0 +1,103 @@
exports.newWebSocketsInterface = function newWebSocketsInterface() {
const LOG_INFO = false
let thisObject = {
initialize: initialize,
finalize: finalize
}
const WEB_SOCKET = require('ws')
let socketServer
let port = global.env.CLIENT_WEB_SOCKETS_INTERFACE_PORT
return thisObject
function finalize() {
socketServer = undefined
}
function initialize() {
setUpWebSocketServer()
}
function setUpWebSocketServer() {
try {
socketServer = new WEB_SOCKET.Server({ port: port })
socketServer.on('connection', onConnection)
function onConnection(socket) {
let lastNonce = -1
if (LOG_INFO === true) {
console.log('New Websocket Connection.')
}
socket.on('message', onMenssage)
function onMenssage(message){
try {
if (LOG_INFO === true) {
console.log('Message Received: ' + message.substring(0, 1000))
}
let messageArray = message.split('|*|')
let origin = messageArray[0]
let nonce = messageArray[1]
let messageToEventServer = messageArray[2]
if (origin === 'Web Browser') {
if (isNaN(nonce) || nonce === "") {
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Nonce is not a Number. message = ' + message.substring(0, 1000))
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Nonce is not a Number. nonce = ' + nonce)
return
}
if (nonce === "1") { // this happens once the browser is restarted, and the server is running since a previous session.
lastNonce = 0
}
if (Number(nonce) < Number(lastNonce)) {
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. message = ' + message.substring(0, 1000))
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. nonce = ' + nonce)
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. lastNonce = ' + lastNonce)
return
}
lastNonce = nonce
try {
JSON.parse(messageToEventServer)
} catch (err) {
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Message received from the browser is not a valid JSON. message = ' + message.substring(0, 1000))
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Message received from the browser is not a valid JSON. messageToEventServer = ' + messageToEventServer)
return
}
let acknowledgeMessage = {
action: 'Acknowledge',
nonce: nonce
}
socket.send(JSON.stringify(acknowledgeMessage))
}
CL.servers.EVENT_SERVER.onMessage(messageToEventServer, onResponse)
function onResponse(message) {
socket.send(message)
}
} catch (err) {
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> Nonce received is less than Last Nonce. err = ' + err.stack)
}
}
}
} catch (err) {
console.log('[ERROR] Client -> Web Sockets Interface -> run -> setUpWebSocketServer -> err.message = ' + err.message.substring(0, 1000))
}
}
}