make proxy work

This commit is contained in:
Jonathan Rainville 2019-08-20 10:29:14 -04:00 committed by Iuri Matias
parent 4533acaaa8
commit 9d3064e3ae
9 changed files with 84 additions and 86 deletions

View File

@ -1,9 +1,7 @@
const path = require('path');
const pkgUp = require('pkg-up');
let shelljs = require('shelljs');
import { IPC } from 'embark-core';
const constants = require('embark-core/constants');
import { AccountParser, dappPath, defaultHost, dockerHostSwap, embarkPath, deconstructUrl } from 'embark-utils';
import {AccountParser, dappPath, defaultHost, dockerHostSwap, embarkPath, deconstructUrl} from 'embark-utils';
export class Simulator {
constructor(options) {
@ -16,12 +14,10 @@ export class Simulator {
run(options) {
let cmds = [];
// TODO change this probably
let useProxy = this.blockchainConfig.proxy || false;
let {host, port} = deconstructUrl(this.blockchainConfig.endpoint);
host = (dockerHostSwap(options.host || host) || defaultHost);
port = (options.port || port || 8545);
port = parseInt(port, 10) + (useProxy ? constants.blockchain.servicePortOnProxy : 0);
port = parseInt(port, 10);
cmds.push("-p " + port);
cmds.push("-h " + host);
@ -36,7 +32,7 @@ export class Simulator {
cmds.push("--mnemonic \"" + (simulatorMnemonic) + "\"");
}
cmds.push("-a " + (options.numAccounts || mnemonicAccount.numAddresses || 10));
cmds.push("-e " + (options.defaultBalance || mnemonicAccount.balance|| 100));
cmds.push("-e " + (options.defaultBalance || mnemonicAccount.balance || 100));
// as ganache-cli documentation explains, the simulatorAccounts configuration overrides a mnemonic
let simulatorAccounts = this.blockchainConfig.simulatorAccounts || options.simulatorAccounts;
@ -44,7 +40,7 @@ export class Simulator {
let web3 = new (require('web3'))();
let parsedAccounts = AccountParser.parseAccountsConfig(simulatorAccounts, web3, dappPath(), this.logger);
parsedAccounts.forEach((account) => {
let cmd = '--account="' + account.privateKey + ','+account.hexBalance + '"';
let cmd = '--account="' + account.privateKey + ',' + account.hexBalance + '"';
cmds.push(cmd);
});
}
@ -52,7 +48,7 @@ export class Simulator {
// adding blocktime only if it is defined in the blockchainConfig or options
let simulatorBlocktime = this.blockchainConfig.simulatorBlocktime || options.simulatorBlocktime;
if (simulatorBlocktime) {
cmds.push("-b \"" + (simulatorBlocktime) +"\"");
cmds.push("-b \"" + (simulatorBlocktime) + "\"");
}
// Setting up network id for simulator from blockchainConfig or options.
@ -62,10 +58,10 @@ export class Simulator {
cmds.push("--networkId " + networkId);
}
this.runCommand(cmds, useProxy, host, port);
this.runCommand(cmds, host, port);
}
runCommand(cmds, useProxy, host, port) {
runCommand(cmds) {
const ganache_main = require.resolve('ganache-cli', {paths: [embarkPath('node_modules')]});
const ganache_json = pkgUp.sync(path.dirname(ganache_main));
const ganache_root = path.dirname(ganache_json);
@ -81,6 +77,6 @@ export class Simulator {
const program = ganache;
console.log(`running: ${programName} ${cmds.join(' ')}`);
shelljs.exec(`node ${program} ${cmds.join(' ')}`, {async : true});
shelljs.exec(`node ${program} ${cmds.join(' ')}`, {async: true});
}
}

View File

@ -12,6 +12,7 @@ class Deployment {
this.logger = embark.logger;
this.plugins = options.plugins;
this.blockchainConfig = this.config.blockchainConfig;
this.errors = [];
this.contractDeployer = new ContractDeployer({
events: this.events,
@ -61,7 +62,7 @@ class Deployment {
deployAll(contracts, contractDependencies, done) {
const self = this;
console.dir("doing deployAll")
// console.dir("doing deployAll")
const contractDeploys = {};
const errors = [];

View File

@ -26,7 +26,7 @@
},
"main": "./dist/index.js",
"scripts": {
"build": "cross-env BABEL_ENV=node babel src --extensions \".ts\" --out-dir dist --root-mode upward --source-maps",
"build": "cross-env BABEL_ENV=node babel src --out-dir dist --root-mode upward --source-maps",
"ci": "npm run qa",
"clean": "npm run reset",
"lint": "npm-run-all lint:*",

View File

@ -6,55 +6,82 @@ import {Proxy} from "./proxy";
const constants = require("embark-core/constants");
export default class ProxyManager {
private logger: Logger;
private events: Events;
private readonly logger: Logger;
private readonly events: Events;
private proxyIpc: IPC;
private rpcProxy: any;
private wsProxy: any;
// private rpcPort: number;
// private wsPort: number;
private readonly host: string;
private readonly rpcPort: number;
private readonly wsPort: number;
private ready: boolean;
constructor(private embark: Embark, _options: any) {
console.log("ALLO");
this.logger = embark.logger;
this.events = embark.events;
this.proxyIpc = new IPC({ipcRole: "client"});
this.ready = false;
this.embark.config.blockchainConfig.rpcPort += constants.blockchain.servicePortOnProxy;
this.embark.config.blockchainConfig.wsPort += constants.blockchain.servicePortOnProxy;
this.host = "localhost";
this.rpcPort = this.embark.config.blockchainConfig.rpcPort + constants.blockchain.servicePortOnProxy;
this.wsPort = this.embark.config.blockchainConfig.wsPort + constants.blockchain.servicePortOnProxy;
this.events.once("blockchain:ready", () => {
console.log("SETUP");
this.setupProxy();
this.events.once("blockchain:started", async () => {
await this.setupProxy();
this.ready = true;
this.events.emit("proxy:ready");
});
this.events.setCommandHandler("blockchain:client:endpoint", async (cb) => {
await this.onReady();
if (!this.embark.config.blockchainConfig.proxy) {
return cb(null, this.embark.config.blockchainConfig.endpoint);
}
// TODO actually check for the wanted connection
cb(null, `http://${this.host}:${this.rpcPort}`);
// cb(null, `ws://${this.host}:${this.wsPort}`);
});
}
public onReady() {
return new Promise((resolve, _reject) => {
if (this.ready) {
return resolve();
}
this.events.once("proxy:ready", () => {
resolve();
});
});
}
private async setupProxy() {
if (this.embark.config.blockchainConfig.proxy) {
if (!this.embark.config.blockchainConfig.proxy) {
return;
}
const addresses = AccountParser.parseAccountsConfig(this.embark.config.blockchainConfig.accounts, false, dappPath(), this.logger);
let wsProxy;
if (this.embark.config.blockchainConfig.wsRPC) {
wsProxy = new Proxy(this.proxyIpc).serve(
this.embark.config.blockchainConfig.wsHost,
this.embark.config.blockchainConfig.wsPort,
true, this.embark.config.blockchainConfig.wsOrigins,
addresses,
this.embark.config.webServerConfig.certOptions);
}
[this.rpcProxy, this.wsProxy] = await Promise.all([
new Proxy(this.proxyIpc).serve(
this.embark.config.blockchainConfig.rpcHost,
this.embark.config.blockchainConfig.rpcPort,
this.host,
this.rpcPort,
false,
null,
addresses,
this.embark.config.webServerConfig.certOptions),
wsProxy,
this.embark.config.webServerConfig.certOptions,
),
this.embark.config.blockchainConfig.wsRPC ? new Proxy(this.proxyIpc).serve(
this.embark.config.blockchainConfig.wsHost,
this.embark.config.blockchainConfig.wsPort,
this.host,
this.wsPort,
true,
this.embark.config.blockchainConfig.wsOrigins,
addresses,
this.embark.config.webServerConfig.certOptions) : null,
]);
return;
}
public shutdownProxy() {

View File

@ -204,13 +204,13 @@ export class Proxy {
this.sendIpcMessage('blockchain:devtxs:sendtx');
}
async serve(host, port, ws, origin, accounts, certOptions={}) {
async serve(endpointHost, endpointPort, localHost, localPort, ws, origin, accounts, certOptions={}) {
const start = Date.now();
await (function waitOnTarget() {
return new Promise(resolve => {
pingEndpoint(
canonicalHost(host),
port,
canonicalHost(endpointHost),
endpointPort,
ws ? 'ws': false,
'http',
origin ? origin.split(',')[0] : undefined,
@ -228,8 +228,8 @@ export class Proxy {
let proxy = httpProxy.createProxyServer({
ssl: certOptions,
target: {
host: canonicalHost(host),
port: port
host: canonicalHost(endpointHost),
port: endpointPort
},
ws: ws,
createWsServerTransformStream: (_req, _proxyReq, _proxyRes) => {
@ -309,8 +309,8 @@ export class Proxy {
return new Promise(resolve => {
server.listen(
port - constants.blockchain.servicePortOnProxy,
host,
localPort,
localHost,
() => { resolve(server); }
);
});

View File

@ -25,6 +25,7 @@ export interface Config {
generationDir: string;
};
blockchainConfig: {
endpoint: string;
accounts: any[];
proxy: boolean;
rpcPort: string | number;

View File

@ -1,3 +1,4 @@
const Web3 = require('web3');
class BlockchainClient {
@ -14,9 +15,13 @@ class BlockchainClient {
// TODO: unclear currently if this belongs here so it's a bit hardcoded for now
this.events.setCommandHandler("blockchain:client:provider", (clientName, cb) => {
const Web3 = require('web3');
var web3 = new Web3("ws://localhost:8556");
cb(null, web3.currentProvider);
this.events.request("blockchain:client:endpoint", (err, endpoint) => {
if (err) {
return cb(err);
}
const web3 = new Web3(endpoint);
cb(null, web3.currentProvider);
});
});
// TODO: maybe not the ideal event to listen to?

View File

@ -4,6 +4,8 @@ const async = require('async');
const Web3 = require('web3');
const embarkJsUtils = require('embarkjs').Utils;
import checkContractSize from "./checkContractSize";
import {AddressUtils} from 'embark-utils';
const {ZERO_ADDRESS} = AddressUtils;
class EthereumBlockchainClient {
@ -56,6 +58,9 @@ class EthereumBlockchainClient {
embarkJsUtils.secureSend(web3, contractObject, {
from: account, gas: 800000
}, true, (err, receipt) => {
if (err) {
return done(err);
}
contract.deployedAddress = receipt.contractAddress;
contract.transactionHash = receipt.transactionHash;
contract.log(`${contract.className.bold.cyan} ${__('deployed at').green} ${receipt.contractAddress.bold.cyan} ${__("using").green} ${receipt.gasUsed} ${__("gas").green} (txHash: ${receipt.transactionHash.bold.cyan})`);

View File

@ -6,10 +6,9 @@ const path = require('path');
const constants = require('embark-core/constants');
const GethClient = require('./gethClient.js');
// const ParityClient = require('./parityClient.js');
// import { Proxy } from './proxy';
import { IPC } from 'embark-core';
import { compact, dappPath, defaultHost, dockerHostSwap, embarkPath, AccountParser} from 'embark-utils';
import { compact, dappPath, defaultHost, dockerHostSwap, embarkPath} from 'embark-utils';
const Logger = require('embark-logger');
// time between IPC connection attempts (in ms)
@ -24,7 +23,6 @@ var Blockchain = function(userConfig, clientClass) {
this.onExitCallback = userConfig.onExitCallback;
this.logger = userConfig.logger || new Logger({logLevel: 'debug', context: constants.contexts.blockchain}); // do not pass in events as we don't want any log events emitted
this.events = userConfig.events;
this.proxyIpc = null;
this.isStandalone = userConfig.isStandalone;
this.certOptions = userConfig.certOptions;
@ -60,8 +58,7 @@ var Blockchain = function(userConfig, clientClass) {
vmdebug: this.userConfig.vmdebug || false,
targetGasLimit: this.userConfig.targetGasLimit || false,
syncMode: this.userConfig.syncMode || this.userConfig.syncmode,
verbosity: this.userConfig.verbosity,
proxy: this.userConfig.proxy
verbosity: this.userConfig.verbosity
};
this.devFunds = null;
@ -103,7 +100,6 @@ var Blockchain = function(userConfig, clientClass) {
this.logger.error(__(spaceMessage, 'genesisBlock'));
process.exit(1);
}
this.initProxy();
this.client = new clientClass({config: this.config, env: this.env, isDev: this.isDev});
this.initStandaloneProcess();
@ -153,35 +149,6 @@ Blockchain.prototype.initStandaloneProcess = function () {
}
};
Blockchain.prototype.initProxy = function () {
if (this.config.proxy) {
this.config.rpcPort += constants.blockchain.servicePortOnProxy;
this.config.wsPort += constants.blockchain.servicePortOnProxy;
}
};
Blockchain.prototype.setupProxy = async function () {
// if (!this.proxyIpc) this.proxyIpc = new IPC({ipcRole: 'client'});
// const addresses = AccountParser.parseAccountsConfig(this.userConfig.accounts, false, dappPath(), this.logger);
// let wsProxy;
// if (this.config.wsRPC) {
// wsProxy = new Proxy(this.proxyIpc).serve(this.config.wsHost, this.config.wsPort, true, this.config.wsOrigins, addresses, this.certOptions);
// }
// [this.rpcProxy, this.wsProxy] = await Promise.all([new Proxy(this.proxyIpc).serve(this.config.rpcHost, this.config.rpcPort, false, null, addresses, this.certOptions), wsProxy]);
};
Blockchain.prototype.shutdownProxy = function () {
// if (!this.config.proxy) {
// return;
// }
// if (this.rpcProxy) this.rpcProxy.close();
// if (this.wsProxy) this.wsProxy.close();
};
Blockchain.prototype.runCommand = function (cmd, options, callback) {
this.logger.info(__("running: %s", cmd.underline).green);
if (this.config.silent) {
@ -257,9 +224,6 @@ Blockchain.prototype.run = function () {
data = data.toString();
if (!self.readyCalled && self.client.isReady(data)) {
self.readyCalled = true;
// if (self.config.proxy) {
// await self.setupProxy();
// }
self.readyCallback();
}
self.logger.info(`${self.client.name}: ${data}`);
@ -297,7 +261,6 @@ Blockchain.prototype.readyCallback = function () {
};
Blockchain.prototype.kill = function () {
this.shutdownProxy();
if (this.child) {
this.child.kill();
}