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

View File

@ -26,7 +26,7 @@
}, },
"main": "./dist/index.js", "main": "./dist/index.js",
"scripts": { "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", "ci": "npm run qa",
"clean": "npm run reset", "clean": "npm run reset",
"lint": "npm-run-all lint:*", "lint": "npm-run-all lint:*",

View File

@ -6,55 +6,82 @@ import {Proxy} from "./proxy";
const constants = require("embark-core/constants"); const constants = require("embark-core/constants");
export default class ProxyManager { export default class ProxyManager {
private logger: Logger; private readonly logger: Logger;
private events: Events; private readonly events: Events;
private proxyIpc: IPC; private proxyIpc: IPC;
private rpcProxy: any; private rpcProxy: any;
private wsProxy: any; private wsProxy: any;
// private rpcPort: number; private readonly host: string;
// private wsPort: number; private readonly rpcPort: number;
private readonly wsPort: number;
private ready: boolean;
constructor(private embark: Embark, _options: any) { constructor(private embark: Embark, _options: any) {
console.log("ALLO");
this.logger = embark.logger; this.logger = embark.logger;
this.events = embark.events; this.events = embark.events;
this.proxyIpc = new IPC({ipcRole: "client"}); this.proxyIpc = new IPC({ipcRole: "client"});
this.ready = false;
this.embark.config.blockchainConfig.rpcPort += constants.blockchain.servicePortOnProxy; this.host = "localhost";
this.embark.config.blockchainConfig.wsPort += constants.blockchain.servicePortOnProxy; 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", () => { this.events.once("blockchain:started", async () => {
console.log("SETUP"); await this.setupProxy();
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() { private async setupProxy() {
if (this.embark.config.blockchainConfig.proxy) { if (!this.embark.config.blockchainConfig.proxy) {
return; return;
} }
const addresses = AccountParser.parseAccountsConfig(this.embark.config.blockchainConfig.accounts, false, dappPath(), this.logger); 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([ [this.rpcProxy, this.wsProxy] = await Promise.all([
new Proxy(this.proxyIpc).serve( new Proxy(this.proxyIpc).serve(
this.embark.config.blockchainConfig.rpcHost, this.embark.config.blockchainConfig.rpcHost,
this.embark.config.blockchainConfig.rpcPort, this.embark.config.blockchainConfig.rpcPort,
this.host,
this.rpcPort,
false, false,
null, null,
addresses, addresses,
this.embark.config.webServerConfig.certOptions), this.embark.config.webServerConfig.certOptions,
wsProxy, ),
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() { public shutdownProxy() {

View File

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

View File

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

View File

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

View File

@ -4,6 +4,8 @@ const async = require('async');
const Web3 = require('web3'); const Web3 = require('web3');
const embarkJsUtils = require('embarkjs').Utils; const embarkJsUtils = require('embarkjs').Utils;
import checkContractSize from "./checkContractSize"; import checkContractSize from "./checkContractSize";
import {AddressUtils} from 'embark-utils';
const {ZERO_ADDRESS} = AddressUtils;
class EthereumBlockchainClient { class EthereumBlockchainClient {
@ -56,6 +58,9 @@ class EthereumBlockchainClient {
embarkJsUtils.secureSend(web3, contractObject, { embarkJsUtils.secureSend(web3, contractObject, {
from: account, gas: 800000 from: account, gas: 800000
}, true, (err, receipt) => { }, true, (err, receipt) => {
if (err) {
return done(err);
}
contract.deployedAddress = receipt.contractAddress; contract.deployedAddress = receipt.contractAddress;
contract.transactionHash = receipt.transactionHash; 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})`); 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 constants = require('embark-core/constants');
const GethClient = require('./gethClient.js'); const GethClient = require('./gethClient.js');
// const ParityClient = require('./parityClient.js'); // const ParityClient = require('./parityClient.js');
// import { Proxy } from './proxy';
import { IPC } from 'embark-core'; 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'); const Logger = require('embark-logger');
// time between IPC connection attempts (in ms) // time between IPC connection attempts (in ms)
@ -24,7 +23,6 @@ var Blockchain = function(userConfig, clientClass) {
this.onExitCallback = userConfig.onExitCallback; 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.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.events = userConfig.events;
this.proxyIpc = null;
this.isStandalone = userConfig.isStandalone; this.isStandalone = userConfig.isStandalone;
this.certOptions = userConfig.certOptions; this.certOptions = userConfig.certOptions;
@ -60,8 +58,7 @@ var Blockchain = function(userConfig, clientClass) {
vmdebug: this.userConfig.vmdebug || false, vmdebug: this.userConfig.vmdebug || false,
targetGasLimit: this.userConfig.targetGasLimit || false, targetGasLimit: this.userConfig.targetGasLimit || false,
syncMode: this.userConfig.syncMode || this.userConfig.syncmode, syncMode: this.userConfig.syncMode || this.userConfig.syncmode,
verbosity: this.userConfig.verbosity, verbosity: this.userConfig.verbosity
proxy: this.userConfig.proxy
}; };
this.devFunds = null; this.devFunds = null;
@ -103,7 +100,6 @@ var Blockchain = function(userConfig, clientClass) {
this.logger.error(__(spaceMessage, 'genesisBlock')); this.logger.error(__(spaceMessage, 'genesisBlock'));
process.exit(1); process.exit(1);
} }
this.initProxy();
this.client = new clientClass({config: this.config, env: this.env, isDev: this.isDev}); this.client = new clientClass({config: this.config, env: this.env, isDev: this.isDev});
this.initStandaloneProcess(); 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) { Blockchain.prototype.runCommand = function (cmd, options, callback) {
this.logger.info(__("running: %s", cmd.underline).green); this.logger.info(__("running: %s", cmd.underline).green);
if (this.config.silent) { if (this.config.silent) {
@ -257,9 +224,6 @@ Blockchain.prototype.run = function () {
data = data.toString(); data = data.toString();
if (!self.readyCalled && self.client.isReady(data)) { if (!self.readyCalled && self.client.isReady(data)) {
self.readyCalled = true; self.readyCalled = true;
// if (self.config.proxy) {
// await self.setupProxy();
// }
self.readyCallback(); self.readyCallback();
} }
self.logger.info(`${self.client.name}: ${data}`); self.logger.info(`${self.client.name}: ${data}`);
@ -297,7 +261,6 @@ Blockchain.prototype.readyCallback = function () {
}; };
Blockchain.prototype.kill = function () { Blockchain.prototype.kill = function () {
this.shutdownProxy();
if (this.child) { if (this.child) {
this.child.kill(); this.child.kill();
} }