Metamask is not connecting local network Localhost 8545 - node.js

I'm building a Web-App using NodeJs. I'm stuck when I tried to connect the local server to metamask. When I try to add new network as mentioned in my. When I try to connect to localhost8545 in chrome extension then it returns this error:
trufle-config.js
var HDWalletProvider = require("truffle-hdwallet-provider");
module.exports = {
// See <https://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
network_id: "*", // Match any network id
port: 8545,
//* gas: 8000000,
//* gasprice: 10000000000,
},
ropstenInfura: {
provider: function() {
return new HDWalletProvider(
process.env.INFURA_ROPSTEN_MNEMONIC,
"https://ropsten.infura.io/v3/" + process.env.INFURA_PROJECT_ID
);
},
network_id: "3",
},
ropstenLocal: {
from: "*********************",
host: "127.0.0.1",
port: 8545,
network_id: "*",
gas: 5000000,
gasPrice: 10000000000,
},
live: {
from: "*******************",
host: "127.0.0.1",
port: 8545,
network_id: "*",
gas: 500000,
gasPrice: 1000000000,
},
},
compilers: {
solc: {
version: "0.4.24",
},
},
};
Ganache-cli

Related

How to create JSON nested Objects using NodeJS and JSON.stringify()

My problem is in the port_password.
{
"server": "0.0.0.0",
"server_ipv6": "::",
"local_address": "127.0.0.1",
"local_port": 1080,
"timeout": 120,
"method": "aes-256-cfb",
"protocol": "origin",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth",
"obfs_param": "",
"redirect": "",
"dns_ipv6": false,
"fast_open": true,
"workers": 1,
"port_password": "{\"10000\":\"pass\",\"10001\":\"pass\",\"10002\":\"pass\",}"
}
The code I used to generate JSON.
account.forEach(ssr => {
portsPasswords += JSON.stringify(ssr.port.toString()) + ':' + JSON.stringify(ssr.password.toString()) + ','
})
I want the output something like this. How can I achieve that using NodeJS and JSON.stringfy()?
{
"server": "0.0.0.0",
"server_ipv6": "::",
"local_address": "127.0.0.1",
"local_port": 1080,
"timeout": 120,
"method": "aes-256-cfb",
"protocol": "origin",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth",
"obfs_param": "",
"redirect": "",
"dns_ipv6": false,
"fast_open": true,
"workers": 1,
"port_password": {
"10000":"pass",
"10001":"pass",
"10002":"pass"
}
}
reduce into an object instead:
const account = [
{ port: 10000, password: 'pass1' },
{ port: 10001, password: 'pass2' },
{ port: 10002, password: 'pass3' }
];
const port_password = account.reduce((a, { port, password }) => {
a[port] = password;
return a;
}, {});
const entireObj = {
"server": "0.0.0.0",
// etc
port_password
};
console.log(JSON.stringify(entireObj));

Unable to create session from org.openqa.selenium.remote.NewSessionPayload, with phantomjs and nightwatch.js

I am trying to execute my test over Phantom JS in nightwatchjs
I am using Selenium server with nightwatchjs and cucumber
I took the following link as a reference-
https://github.com/nightwatchjs/nightwatch/wiki/Running-tests-in-PhantomJS
There are other answers as well but none is matching mine. this might be a configuration issue but I am not able to cut it. Can someone please help me out here.
error:
NFO Request: POST /wd/hub/session
- data: {"desiredCapabilities":{"browserName":"phantomjs","javascriptEnabled":true,"acceptSslCerts":true,"platform":"ANY","phantomjs.binary.path":"/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs","phantomjs.cli.args":["--ignore-ssl-errors=true"],"silent":false}}
- headers: {"Content-Type":"application/json; charset=utf-8","Content-Length":270}
ERROR Response 500 POST /wd/hub/session (482ms) { value:
{ message: 'Unable to create session from org.openqa.selenium.remote.NewSessionPayload#5c510db\nBuild info: version: \'3.12.0\', revision: \'7c6e0b3\', time: \'2018-05-08T15:15:08.936Z\'\nSystem info: host: \'Chirags-MacBook-Pro.local\', ip: \'fe80:0:0:0:142a:4efe:d208:27ae%en0\', os.name: \'Mac OS X\', os.arch: \'x86_64\', os.version: \'10.13.5\', java.version: \'1.8.0_171\'\nDriver info: driver.version: unknown',
error: 'session not created' },
status: 33 }
{ Error [ERR_UNHANDLED_ERROR]: Unhandled error. ([object Object])
at ClientManager.emit (events.js:171:17)
at Nightwatch.<anonymous> (/Users/prateik/Codebase/NightCuke/node_modules/nightwatch/lib/runner/clientmanager.js:68:10)
at Object.onceWrapper (events.js:273:13)
at Nightwatch.emit (events.js:182:13)
at HttpRequest.<anonymous> (/Users/prateik/Codebase/NightCuke/node_modules/nightwatch/lib/index.js:501:10)
at HttpRequest.emit (events.js:182:13)
at IncomingMessage.<anonymous> (/Users/prateik/Codebase/NightCuke/node_modules/nightwatch/lib/http/request.js:172:16)
at IncomingMessage.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1086:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
context:
{ message: 'Connection refused! Is selenium server started?\n',
data: { value: [Object], status: 33 } } }
it says driver.version:unknown, can this be the issue?
all the components are at their latest versions
"cucumber": "^4.0.0",
"nightwatch": "^0.9.21",
"nightwatch-cucumber": "^9.1.2",
"phantomjs-prebuilt": "^2.1.16",
"selenium-server": "^3.12.0"
nightwatch.conf.js
//Nightwatch Configuration
const seleniumServer = require('selenium-server')
const phantomjs = require('phantomjs-prebuilt')
const chromedriver = require('chromedriver')
const geckodriver = require('geckodriver')
require('nightwatch-cucumber')({
cucumberArgs: [
'--require-module', 'babel-core/register',
'--format', 'node_modules/cucumber-pretty',
'--require', 'hooks.js',
'--require', 'features/step_definitions',
'--format-options', '{"colorsEnabled":false}',
'--format', 'json:reports/cucumber.json',
'features'
],
nightwatchOutput: true
})
module.exports = {
// src_folders:'features',
output_folder: 'reports',
custom_assertions_path: '',
page_objects_path: 'page_objects/',
live_output: true,
disable_colors: false,
selenium: {
start_process: true,
server_path: seleniumServer.path,
log_path: '/reports',
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': chromedriver.path,
'webdriver.gecko.driver' : geckodriver.path,
"webdriver.edge.driver" : "",
}
},
test_settings: {
default: {
launch_url: 'http://localhost',
selenium_port: 4444,
selenium_host: '127.0.0.1',
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true,
silent:false
//chromeOptions:['start-fullscreen']
},
selenium: {},
screenshots: {
enabled: true,
on_failure: true,
path: 'screenshots'
}
},
phantomjs: {
//launch_url: 'http://localhost/',
selenium_port: 4444,
selenium_host: '127.0.0.1',
desiredCapabilities: {
browserName: 'phantomjs',
javascriptEnabled: true,
acceptSslCerts: true,
//platform: 'Mac OS X',
"phantomjs.binary.path": phantomjs.path,
"phantomjs.cli.args" : ['--ignore-ssl-errors=true']
},
},
firefox: {
desiredCapabilities: {
browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
}
}
}

How to broadcast same messages to multiple interfaces in Mosca

I have 2 interfaces, one mqtt and one for websocket. I noticed if I have a backend, the mqtt does not route to websocket.
I created the mosca server as below:
server = new mosca.Server(
{
interfaces:
[
{ type: "mqtt", port: 1883 },
{
type: "mqtts",
port: 8443,
credentials: { keyPath: SECURE_KEY, certPath: SECURE_CERT }
},
{ type: "http", port: 4000, bundle: true }
],
onQoS2publish: "noack",
logger: { name: 'MoscaServer', level: 'debug' },
backend: {
type: "mqtt",
json: false,
mqtt: require("mqtt"),
key: filesys.readFileSync(__dirname + "/certs/private.key"),
cert: filesys.readFileSync(__dirname + "/certs/cert.pem"),
ca: filesys.readFileSync(__dirname + "/certs/rootCA.cer"),
clientId: "randomClientId",
port: 8883,
host: "<aws IOT endpoint>.iot.<aws region>.amazonaws.com",
rejectUnauthorized: false,
protocol: "mqtts"
},
}
);
What do I need to do to route between all the 3: mqtt, websocket and the backend?
Thanks!

Migration not filling out "networks": {}, field in .json file

When I run truffle migrate all my .json files in my build/contracts directory are missing their network field. Im trying to deploy to testrpc.
This is my truffle.js file:
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*", // Match any network id
gas: 4500000
}
},
solc: {
optimizer: {
enabled: true,
runs: 200
}
},
mocha: {
bail: true
}
};
Does anyone know what might be causing this?
Thanks!

Mongoose connection authentication failed

With this help, I created a super user in the mongo shell: Create Superuser in mongo
user: "try1"
passw: "hello"
In mongo cmd, I have 3 databases: 'admin', 'myDatabase' and 'local'.
Now I try to use this authorized connection to the database called 'myDatabase'.
mongoose.connect('mongodb://try1:hello#localhost:27017/myDatabase');
But this is the error I get:
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
Mongoose disconnected
Mongoose disconnected through ${msg}
I had the same problem many hours ago, and after all I solve it. My code is:
mongoose.createConnection(
"mongodb://localhost:27017/dbName",
{
"auth": {
"authSource": "admin"
},
"user": "admin",
"pass": "password"
}
);
Further to #kartGIS, I've added one more option to make the connection code perfect as possible.
mongoose.connect("mongodb://localhost:27017/databaseName", {
"auth": { "authSource": "admin" },
"user": "username",
"pass": "password",
"useMongoClient": true
});
This is the correct answer now. others are not completely correct.
await mongoose.connect("mongodb://localhost:27017/db", {
poolSize: 10,
authSource: "admin",
user: "admin",
pass: "password",
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
Syntax:
await mongoose.connect('mongodb://username:password#host:port/database?authSource=admin');
Example:
await mongoose.connect('mongodb://myUser:myPassword#localhost:27017/myDataBase?authSource=admin');
Working fine for me on Mongodb 4.2 and Mongoose 5.7.13
Node.js
const Connect = async () => {
let url = "mongodb://localhost:27017/test_db";
try {
let client = await Mongoose.connect( url, {
poolSize: 10,
authSource: "admin",
user: "root",
pass: "root123",
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
} );
log( "Database is connected!" );
} catch ( error ) {
log( error.stack );
process.exit( 1 );
}
}
Connect();
/etc/mongod.conf
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
net:
port: 27017
bindIp: 0.0.0.0
setParameter:
enableLocalhostAuthBypass: false
security:
authorization: enabled
Database User
use admin;
db.createUser(
{
user: "root",
pwd: "root123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
show users;
{
"_id": "admin.root",
"userId": UUID( "5db3aafd-b1fd-4bea-925e-8a4bfb709f22" ),
"user": "root",
"db": "admin",
"roles": [ {
"role": "userAdminAnyDatabase",
"db": "admin"
},
{
"role": "readWriteAnyDatabase",
"db": "admin"
}
],
"mechanisms": [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
I have the same problem, and it solved by removing the 'authSource' param
/* Not working */
mongoose.connect("mongodb://localhost:27017/test", {
"auth": { "authSource": "admin" },
"user": "admin",
"pass": "admin123",
"useMongoClient": true
});
/* Working */
mongoose.connect("mongodb://localhost:27017/test", {
"user": "admin",
"pass": "admin123",
"useMongoClient": true
});
Tested on Mongoose-v5.0.0.
THIS ANSWER FOR MONGOOSE 6.7.0! USED IN NUXT 3
.env PART
MONGO_URI = "mongodb://localhost:27017/MyBeautifulDB"
MONGO_USERNAME = "mongoadmin"
MONGO_PASSWORD = "mystrongpassword"
DB CONNECTION PART
import mongoose from 'mongoose';
export default async (_nitroApp) => {
const config = useRuntimeConfig();
mongoose.connect(config.MONGO_URI, {
maxPoolSize: 10,
authSource: "admin",
user: config.MONGO_USERNAME,
pass: config.MONGO_PASSWORD
})
.then(() => console.log('Connected to DB'))
.catch((e) => console.log(e));
}
nuxt.config.ts - Register your db connection file to configuration.
export default defineNuxtConfig({
runtimeConfig: {
MONGO_URI: process.env.MONGO_URI,
},
nitro: {
plugins: ['#/server/db/index.ts']
}
})
I got MongoParseError: credentials must be an object with 'username' and 'password' properties when used above answers.
Add username password to auth object solved the issue
try {
await connect("mongodb://localhost:27017/dbname", {
auth: { username: "root", password: "example" },
authSource: "admin",
});
console.log("Connected to mongo db");
} catch (error) {
console.error("Error connecting to mongodb", error);
}
mongodb version 5.0.2
mongoose 6.0.4
Respectively, if your authSource is the database ('myDB' in the example) itself and you are trying to use the ConnectionOption dbName, you have to match authSource.
await mongoose.connect('mongodb://localhost:27017,' {
dbName: 'myDB',
user: 'myUser',
pass: 'asldjaskdj'
);
Will fail with error:
{
"msg": "Authentication failed",
"attr": {
"mechanism": "SCRAM-SHA-1",
"principalName": "myUser",
"authenticationDatabase": "admin",
"client": "...",
"result": "UserNotFound: Could not find user \"myUser\" for db \"admin\""
}
}
Adding authSource: 'myDB' to the connect options will work. Example:
await mongoose.connect('mongodb://localhost:27017,' {
dbName: 'myDB',
authSource: 'myDB',
user: 'myUser',
pass: 'asldjaskdj'
);
I had the same problem. I am using an older MongoDB instance. I simply added authSource=admin to the connection string and it solved the problem.
According to the latest documentation, it should be like this:
mongoose.connect("mongodb://localhost:27017/databaseName", {
"user": "username",
"pass": "password",
"authSource": "databaseName" // users are scoped to DBs
});
Tested on mongoose6.x.x
works for me. i use local database, and mongoose ver 6.9.1
.env file:
DB_HOST=127.0.0.1:27017
DB_NAME=blabla
DB_USER=blablabla
DB_PWD=blablablabla
js file:
const DB = `mongodb://${process.env.DB_HOST}/${process.env.DB_NAME}`;
mongoose
.connect(DB, {
authSource: 'admin',
user: process.env.DB_USER,
pass: process.env.DB_PWD,
})
.then(() => {
console.log('Connected to database.');
})
.catch((err) => {
console.log(err.message);
});
NOTE
This answer is not answering original question but trying to help people in similar situation using NestJS
NestJS
#Module({
imports: [
MongooseModule.forRoot(
'mongodb://mongo:27017/test',
{
auth: {
username: 'root',
password: 'test',
},
authSource: 'admin',
},
),
],
})
export class AppModule {}
I also faced the same issue but resolved it with this
mongoose.connect(mongodb://${dbUser}:${dbPwd}#${dbHost}:${dbPort}/userInfo?authSource=admin). Assuming you have the authentication setup in mongodb.

Resources