refactor(@embark/blockchain-process): introduce package for blockchain-process module

This commit is contained in:
Pascal Precht 2019-05-08 13:19:25 +02:00 committed by Iuri Matias
parent f9d7a3f41b
commit f868d1216d
23 changed files with 251 additions and 139 deletions

View File

@ -0,0 +1,4 @@
engine-strict = true
package-lock = false
save-exact = true
scripts-prepend-node-path = true

View File

@ -0,0 +1,6 @@
# `embark-blockchain-process`
> Blockchain Process abstraction for Embark
Visit [embark.status.im](https://embark.status.im/) to get started with
[Embark](https://github.com/embark-framework/embark).

View File

@ -0,0 +1,83 @@
{
"name": "embark-blockchain-process",
"version": "4.1.0-beta.0",
"author": "Iuri Matias <iuri.matias@gmail.com>",
"contributors": [],
"description": "Blockchain process abstraction for Embark",
"homepage": "https://github.com/embark-framework/embark/tree/master/packages/embark-blockchain-process#readme",
"bugs": "https://github.com/embark-framework/embark/issues",
"keywords": [
"blockchain",
"dapps",
"ethereum",
"ipfs",
"serverless",
"solc",
"solidity"
],
"files": [
"dist"
],
"license": "MIT",
"repository": {
"directory": "packages/embark-blockchain-process",
"type": "git",
"url": "https://github.com/embark-framework/embark.git"
},
"main": "./dist/index.js",
"scripts": {
"build": "cross-env BABEL_ENV=node babel src --extensions \".js\" --out-dir dist --root-mode upward --source-maps",
"ci": "npm run qa",
"clean": "npm run reset",
"lint": "npm-run-all lint:*",
"lint:js": "eslint src/",
"// lint:ts": "tslint -c tslint.json \"src/**/*.ts\"",
"package": "npm pack",
"// qa": "npm-run-all lint typecheck build package",
"qa": "npm-run-all lint build package",
"reset": "npx rimraf dist embark-*.tgz package",
"start": "npm run watch",
"// typecheck": "tsc",
"watch": "run-p watch:*",
"watch:build": "npm run build -- --verbose --watch",
"// watch:typecheck": "npm run typecheck -- --preserveWatchOutput --watch"
},
"eslintConfig": {
"extends": "../../.eslintrc.json"
},
"dependencies": {
"@babel/runtime-corejs2": "7.3.1",
"async": "2.6.1",
"embark-core": "^4.1.0-beta.0",
"embark-i18n": "^4.1.0-beta.0",
"embark-logger": "^4.1.0-beta.0",
"embark-utils": "^4.1.0-beta.0",
"ethereumjs-tx": "1.3.7",
"ethereumjs-util": "6.0.0",
"http-proxy": "1.17.0",
"netcat": "1.3.5",
"node-http-proxy-json": "0.1.6",
"pkg-up": "2.0.0",
"pump": "3.0.0",
"shelljs": "0.5.3",
"semver": "5.6.0",
"simples": "0.8.8",
"stream-json": "1.1.3",
"ws": "6.1.2"
},
"devDependencies": {
"@babel/cli": "7.2.3",
"@babel/core": "7.2.2",
"cross-env": "5.2.0",
"eslint": "5.7.0",
"npm-run-all": "4.1.5",
"rimraf": "2.6.3",
"tslint": "5.16.0",
"typescript": "3.4.5"
},
"engines": {
"node": ">=8.12.0",
"npm": ">=6.4.1",
"yarn": ">=1.12.3"
}
}

View File

@ -2,11 +2,10 @@ import { __ } from 'embark-i18n';
const async = require('async'); const async = require('async');
const {spawn, exec} = require('child_process'); const {spawn, exec} = require('child_process');
const path = require('path'); const path = require('path');
const fs = require('../../core/fs.js');
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');
const Proxy = require('./proxy'); import { Proxy } from './proxy';
import { IPC } from 'embark-core'; import { IPC } from 'embark-core';
import { compact, defaultHost, dockerHostSwap, AccountParser} from 'embark-utils'; import { compact, defaultHost, dockerHostSwap, AccountParser} from 'embark-utils';
@ -16,7 +15,7 @@ const Logger = require('embark-logger');
const IPC_CONNECT_INTERVAL = 2000; const IPC_CONNECT_INTERVAL = 2000;
/*eslint complexity: ["error", 50]*/ /*eslint complexity: ["error", 50]*/
var Blockchain = function(userConfig, clientClass) { var Blockchain = function(userConfig, clientClass, fs) {
this.userConfig = userConfig; this.userConfig = userConfig;
this.env = userConfig.env || 'development'; this.env = userConfig.env || 'development';
this.isDev = userConfig.isDev; this.isDev = userConfig.isDev;
@ -27,6 +26,7 @@ var Blockchain = function(userConfig, clientClass) {
this.proxyIpc = null; this.proxyIpc = null;
this.isStandalone = userConfig.isStandalone; this.isStandalone = userConfig.isStandalone;
this.certOptions = userConfig.certOptions; this.certOptions = userConfig.certOptions;
this.fs = fs;
let defaultWsApi = clientClass.DEFAULTS.WS_API; let defaultWsApi = clientClass.DEFAULTS.WS_API;
@ -81,9 +81,9 @@ var Blockchain = function(userConfig, clientClass) {
if (this.env === 'development') { if (this.env === 'development') {
this.isDev = true; this.isDev = true;
} else { } else {
this.config.genesisBlock = fs.embarkPath("templates/boilerplate/config/privatenet/genesis.json"); this.config.genesisBlock = this.fs.embarkPath("templates/boilerplate/config/privatenet/genesis.json");
} }
this.config.datadir = fs.dappPath(".embark/development/datadir"); this.config.datadir = this.fs.dappPath(".embark/development/datadir");
this.config.wsOrigins = this.config.wsOrigins || "http://localhost:8000"; this.config.wsOrigins = this.config.wsOrigins || "http://localhost:8000";
this.config.rpcCorsDomain = this.config.rpcCorsDomain || "http://localhost:8000"; this.config.rpcCorsDomain = this.config.rpcCorsDomain || "http://localhost:8000";
this.config.targetGasLimit = 8000000; this.config.targetGasLimit = 8000000;
@ -104,7 +104,7 @@ var Blockchain = function(userConfig, clientClass) {
process.exit(1); process.exit(1);
} }
this.initProxy(); 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, fs: this.fs});
this.initStandaloneProcess(); this.initStandaloneProcess();
}; };
@ -131,7 +131,7 @@ Blockchain.prototype.initStandaloneProcess = function () {
} }
}); });
this.ipc = new IPC({ipcRole: 'client', fs}); this.ipc = new IPC({ipcRole: 'client', fs: this.fs});
// Wait for an IPC server to start (ie `embark run`) by polling `.connect()`. // Wait for an IPC server to start (ie `embark run`) by polling `.connect()`.
// Do not kill this interval as the IPC server may restart (ie restart // Do not kill this interval as the IPC server may restart (ie restart
@ -161,9 +161,9 @@ Blockchain.prototype.initProxy = function () {
}; };
Blockchain.prototype.setupProxy = async function () { Blockchain.prototype.setupProxy = async function () {
if (!this.proxyIpc) this.proxyIpc = new IPC({ipcRole: 'client', fs}); if (!this.proxyIpc) this.proxyIpc = new IPC({ipcRole: 'client', fs: this.fs});
const addresses = AccountParser.parseAccountsConfig(this.userConfig.accounts, false, fs.dappPath(), this.logger); const addresses = AccountParser.parseAccountsConfig(this.userConfig.accounts, false, this.fs.dappPath(), this.logger);
let wsProxy; let wsProxy;
if (this.config.wsRPC) { if (this.config.wsRPC) {
@ -304,7 +304,7 @@ Blockchain.prototype.kill = function () {
}; };
Blockchain.prototype.checkPathLength = function () { Blockchain.prototype.checkPathLength = function () {
let dappPath = fs.dappPath(''); let dappPath = this.fs.dappPath('');
if (dappPath.length > 66) { if (dappPath.length > 66) {
// this.logger.error is captured and sent to the console output regardless of silent setting // this.logger.error is captured and sent to the console output regardless of silent setting
this.logger.error("===============================================================================".yellow); this.logger.error("===============================================================================".yellow);
@ -403,7 +403,7 @@ Blockchain.prototype.initChainAndGetAddress = function (callback) {
async.waterfall([ async.waterfall([
function makeDir(next) { function makeDir(next) {
fs.mkdirp(self.datadir, (err, _result) => { this.fs.mkdirp(self.datadir, (err, _result) => {
next(err); next(err);
}); });
}, },
@ -450,14 +450,14 @@ Blockchain.prototype.initChainAndGetAddress = function (callback) {
}); });
}; };
var BlockchainClient = function(userConfig, clientName, env, certOptions, onReadyCallback, onExitCallback, logger, _events, isStandalone) { export function BlockchainClient(userConfig, options) {
if ((userConfig === {} || JSON.stringify(userConfig) === '{"enabled":true}') && env !== 'development') { if ((userConfig === {} || JSON.stringify(userConfig) === '{"enabled":true}') && options.env !== 'development') {
logger.info("===> " + __("warning: running default config on a non-development environment")); options.logger.info("===> " + __("warning: running default config on a non-development environment"));
} }
// if client is not set in preferences, default is geth // if client is not set in preferences, default is geth
if (!userConfig.ethereumClientName) userConfig.ethereumClientName = constants.blockchain.clients.geth; if (!userConfig.ethereumClientName) userConfig.ethereumClientName = constants.blockchain.clients.geth;
// if clientName is set, it overrides preferences // if clientName is set, it overrides preferences
if (clientName) userConfig.ethereumClientName = clientName; if (options.clientName) userConfig.ethereumClientName = options.clientName;
// Choose correct client instance based on clientName // Choose correct client instance based on clientName
let clientClass; let clientClass;
switch (userConfig.ethereumClientName) { switch (userConfig.ethereumClientName) {
@ -473,13 +473,11 @@ var BlockchainClient = function(userConfig, clientName, env, certOptions, onRead
process.exit(1); process.exit(1);
} }
userConfig.isDev = (userConfig.isDev || userConfig.default); userConfig.isDev = (userConfig.isDev || userConfig.default);
userConfig.env = env; userConfig.env = options.env;
userConfig.onReadyCallback = onReadyCallback; userConfig.onReadyCallback = options.onReadyCallback;
userConfig.onExitCallback = onExitCallback; userConfig.onExitCallback = options.onExitCallback;
userConfig.logger = logger; userConfig.logger = options.logger;
userConfig.certOptions = certOptions; userConfig.certOptions = options.certOptions;
userConfig.isStandalone = isStandalone; userConfig.isStandalone = options.isStandalone;
return new Blockchain(userConfig, clientClass); return new Blockchain(userConfig, clientClass, options.fs);
}; }
module.exports = BlockchainClient;

View File

@ -1,7 +1,7 @@
import * as i18n from 'embark-i18n'; import * as i18n from 'embark-i18n';
import { ProcessWrapper } from 'embark-core'; import { ProcessWrapper } from 'embark-core';
const BlockchainClient = require('./blockchain');
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
import { BlockchainClient } from './blockchain';
let blockchainProcess; let blockchainProcess;
@ -13,18 +13,22 @@ class BlockchainProcess extends ProcessWrapper {
this.env = options.env; this.env = options.env;
this.isDev = options.isDev; this.isDev = options.isDev;
this.certOptions = options.certOptions; this.certOptions = options.certOptions;
this.embark = options.embark;
i18n.setOrDetectLocale(options.locale); i18n.setOrDetectLocale(options.locale);
this.blockchainConfig.silent = true; this.blockchainConfig.silent = true;
this.blockchain = BlockchainClient( this.blockchain = BlockchainClient(
this.blockchainConfig, this.blockchainConfig,
this.client, {
this.env, clientName: this.client,
this.certOptions, env: this.env,
this.blockchainReady.bind(this), certOptions: this.certOptions,
this.blockchainExit.bind(this), onReadyCallback: this.blockchainReady.bind(this),
console onExitCallback: this.blockchainExit.bind(this),
logger: console,
fs: this.embark.fs
}
); );
this.blockchain.run(); this.blockchain.run();

View File

@ -1,9 +1,9 @@
import { __ } from 'embark-i18n'; import { __ } from 'embark-i18n';
import { ProcessLauncher } from 'embark-core'; import { ProcessLauncher } from 'embark-core';
import {joinPath} from 'embark-utils'; import { joinPath } from 'embark-utils';
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
class BlockchainProcessLauncher { export class BlockchainProcessLauncher {
constructor (options) { constructor (options) {
this.events = options.events; this.events = options.events;
@ -79,5 +79,3 @@ class BlockchainProcessLauncher {
} }
} }
module.exports = BlockchainProcessLauncher;

View File

@ -1,7 +1,6 @@
import { __ } from 'embark-i18n'; import { __ } from 'embark-i18n';
const async = require('async'); const async = require('async');
const {exec, spawn} = require('child_process'); const {exec, spawn} = require('child_process');
const fs = require('../../core/fs');
const path = require('path'); const path = require('path');
const GethMiner = require('./miner'); const GethMiner = require('./miner');
const semver = require('semver'); const semver = require('semver');
@ -35,6 +34,7 @@ class GethClient {
this.versSupported = DEFAULTS.VERSIONS_SUPPORTED; this.versSupported = DEFAULTS.VERSIONS_SUPPORTED;
this.httpReady = false; this.httpReady = false;
this.wsReady = !this.config.wsRPC; this.wsReady = !this.config.wsRPC;
this.fs = options.fs;
} }
isReady(data) { isReady(data) {
@ -79,7 +79,7 @@ class GethClient {
} }
if (config.account && config.account.password) { if (config.account && config.account.password) {
const resolvedPath = path.resolve(fs.dappPath(), config.account.password); const resolvedPath = path.resolve(this.fs.dappPath(), config.account.password);
cmd.push(`--password=${resolvedPath}`); cmd.push(`--password=${resolvedPath}`);
} }
@ -87,13 +87,13 @@ class GethClient {
cmd.push("--verbosity=" + config.verbosity); cmd.push("--verbosity=" + config.verbosity);
} }
cmd.push(`--ipcpath=${fs.ipcPath('geth.ipc', true)}`); cmd.push(`--ipcpath=${this.fs.ipcPath('geth.ipc', true)}`);
return cmd; return cmd;
} }
getMiner() { getMiner() {
return new GethMiner({datadir: this.config.datadir}); return new GethMiner({datadir: this.config.datadir, fs: this.fs});
} }
getBinaryPath() { getBinaryPath() {
@ -392,3 +392,4 @@ class GethClient {
} }
module.exports = GethClient; module.exports = GethClient;

View File

@ -1,11 +1,15 @@
import { __ } from 'embark-i18n'; import { __ } from 'embark-i18n';
const async = require('async'); const async = require('async');
const utils = require('../../utils/utils.js'); const { normalizeInput, buildUrlFromConfig } = require('embark-utils');
const {normalizeInput, buildUrlFromConfig} = require('embark-utils');
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
const BlockchainProcessLauncher = require('./blockchainProcessLauncher'); import { BlockchainProcessLauncher } from './blockchainProcessLauncher';
import { pingEndpoint } from './utils';
class BlockchainModule { export { BlockchainClient } from './blockchain';
export { Simulator } from './simulator';
export { Proxy } from './proxy';
export default class BlockchainModule {
constructor(embark, options) { constructor(embark, options) {
this.logger = embark.logger; this.logger = embark.logger;
@ -84,12 +88,12 @@ class BlockchainModule {
next(); next();
}); });
}, },
function pingEndpoint(next) { function _pingEndpoint(next) {
if (!self.contractsConfig || !self.contractsConfig.deployment || !self.contractsConfig.deployment.host) { if (!self.contractsConfig || !self.contractsConfig.deployment || !self.contractsConfig.deployment.host) {
return next(); return next();
} }
const {host, port, type, protocol} = self.contractsConfig.deployment; const {host, port, type, protocol} = self.contractsConfig.deployment;
utils.pingEndpoint(host, port, type, protocol, self.blockchainConfig.wsOrigins.split(',')[0], next); pingEndpoint(host, port, type, protocol, self.blockchainConfig.wsOrigins.split(',')[0], next);
} }
], function(err) { ], function(err) {
if (err === true || err === undefined) { if (err === true || err === undefined) {
@ -147,7 +151,5 @@ class BlockchainModule {
cb(); cb();
}); });
} }
} }
module.exports = BlockchainModule;

View File

@ -1,5 +1,4 @@
const async = require('async'); const async = require('async');
const fs = require('../../core/fs');
const NetcatClient = require('netcat/client'); const NetcatClient = require('netcat/client');
//Constants //Constants
@ -20,6 +19,7 @@ class GethMiner {
// In the meantime, just set an empty config object // In the meantime, just set an empty config object
this.config = {}; this.config = {};
this.datadir = options.datadir; this.datadir = options.datadir;
this.fs = options.fs;
self.interval = null; self.interval = null;
self.callback = null; self.callback = null;
self.started = null; self.started = null;
@ -44,7 +44,7 @@ class GethMiner {
} }
} }
const ipcPath = fs.ipcPath('geth.ipc', true); const ipcPath = this.fs.ipcPath('geth.ipc', true);
this.client = new NetcatClient(); this.client = new NetcatClient();
this.client.unixSocket(ipcPath) this.client.unixSocket(ipcPath)

View File

@ -1,6 +1,5 @@
import { __ } from 'embark-i18n'; import { __ } from 'embark-i18n';
const async = require('async'); const async = require('async');
const fs = require('../../core/fs.js');
const path = require('path'); const path = require('path');
const os = require('os'); const os = require('os');
const semver = require('semver'); const semver = require('semver');
@ -53,6 +52,7 @@ class ParityClient {
this.prettyName = "Parity-Ethereum (https://github.com/paritytech/parity-ethereum)"; this.prettyName = "Parity-Ethereum (https://github.com/paritytech/parity-ethereum)";
this.bin = this.config.ethereumClientBin || DEFAULTS.BIN; this.bin = this.config.ethereumClientBin || DEFAULTS.BIN;
this.versSupported = DEFAULTS.VERSIONS_SUPPORTED; this.versSupported = DEFAULTS.VERSIONS_SUPPORTED;
this.fs = options.fs;
} }
isReady(data) { isReady(data) {
@ -262,7 +262,7 @@ class ParityClient {
const keysDataDir = datadir + '/keys/DevelopmentChain'; const keysDataDir = datadir + '/keys/DevelopmentChain';
async.waterfall([ async.waterfall([
function makeDir(next) { function makeDir(next) {
fs.mkdirp(keysDataDir, (err, _result) => { this.fs.mkdirp(keysDataDir, (err, _result) => {
next(err); next(err);
}); });
}, },
@ -270,7 +270,7 @@ class ParityClient {
self.createDevAccount(keysDataDir, next); self.createDevAccount(keysDataDir, next);
}, },
function mkDevPasswordDir(next) { function mkDevPasswordDir(next) {
fs.mkdirp(path.dirname(self.config.account.devPassword), (err, _result) => { this.fs.mkdirp(path.dirname(self.config.account.devPassword), (err, _result) => {
next(err); next(err);
}); });
}, },
@ -278,12 +278,12 @@ class ParityClient {
if (!self.config.account.password) { if (!self.config.account.password) {
return next(null, os.EOL + 'dev_password'); return next(null, os.EOL + 'dev_password');
} }
fs.readFile(fs.dappPath(self.config.account.password), {encoding: 'utf8'}, (err, content) => { this.fs.readFile(this.fs.dappPath(self.config.account.password), {encoding: 'utf8'}, (err, content) => {
next(err, os.EOL + content); next(err, os.EOL + content);
}); });
}, },
function updatePasswordFile(passwordList, next) { function updatePasswordFile(passwordList, next) {
fs.writeFile(self.config.account.devPassword, passwordList, next); this.fs.writeFile(self.config.account.devPassword, passwordList, next);
} }
], (err) => { ], (err) => {
callback(err); callback(err);
@ -292,7 +292,7 @@ class ParityClient {
createDevAccount(keysDataDir, cb) { createDevAccount(keysDataDir, cb) {
const devAccountWallet = keysDataDir + '/dev.wallet'; const devAccountWallet = keysDataDir + '/dev.wallet';
fs.writeFile(devAccountWallet, JSON.stringify(DEFAULTS.DEV_WALLET), function(err) { this.fs.writeFile(devAccountWallet, JSON.stringify(DEFAULTS.DEV_WALLET), function(err) {
if (err) { if (err) {
return cb(err); return cb(err);
} }

View File

@ -3,19 +3,19 @@
require('./httpProxyOverride'); require('./httpProxyOverride');
const Asm = require('stream-json/Assembler'); const Asm = require('stream-json/Assembler');
import { __ } from 'embark-i18n'; import { __ } from 'embark-i18n';
import {canonicalHost, timer} from 'embark-utils'; import { canonicalHost, timer } from 'embark-utils';
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
const {Duplex} = require('stream'); const {Duplex} = require('stream');
const http = require('http'); const http = require('http');
const httpProxy = require('http-proxy'); const httpProxy = require('http-proxy');
const {parser: jsonParser} = require('stream-json'); const {parser: jsonParser} = require('stream-json');
const pump = require('pump'); const pump = require('pump');
const utils = require('../../utils/utils');
const WsParser = require('simples/lib/parsers/ws'); const WsParser = require('simples/lib/parsers/ws');
const WsWrapper = require('simples/lib/ws/wrapper'); const WsWrapper = require('simples/lib/ws/wrapper');
const modifyResponse = require('node-http-proxy-json'); const modifyResponse = require('node-http-proxy-json');
const Transaction = require('ethereumjs-tx'); const Transaction = require('ethereumjs-tx');
const ethUtil = require('ethereumjs-util'); const ethUtil = require('ethereumjs-util');
import { pingEndpoint } from './utils';
const METHODS_TO_MODIFY = {accounts: 'eth_accounts'}; const METHODS_TO_MODIFY = {accounts: 'eth_accounts'};
const REQUEST_TIMEOUT = 5000; const REQUEST_TIMEOUT = 5000;
@ -53,7 +53,7 @@ const parseJsonMaybe = (string) => {
return object; return object;
}; };
class Proxy { export class Proxy {
constructor(ipc) { constructor(ipc) {
this.ipc = ipc; this.ipc = ipc;
this.commList = {}; this.commList = {};
@ -209,7 +209,7 @@ class Proxy {
const start = Date.now(); const start = Date.now();
await (function waitOnTarget() { await (function waitOnTarget() {
return new Promise(resolve => { return new Promise(resolve => {
utils.pingEndpoint( pingEndpoint(
canonicalHost(host), canonicalHost(host),
port, port,
ws ? 'ws': false, ws ? 'ws': false,
@ -317,5 +317,3 @@ class Proxy {
}); });
} }
} }
module.exports = Proxy;

View File

@ -1,18 +1,18 @@
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');
let Proxy = require('./proxy'); import { Proxy } from './proxy';
import { IPC } from 'embark-core'; import { IPC } from 'embark-core';
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
import {defaultHost, dockerHostSwap} from 'embark-utils'; import { defaultHost, dockerHostSwap } from 'embark-utils';
const fs = require('../../core/fs.js');
const { AccountParser } = require('embark-utils'); const { AccountParser } = require('embark-utils');
class Simulator { export class Simulator {
constructor(options) { constructor(options) {
this.blockchainConfig = options.blockchainConfig; this.blockchainConfig = options.blockchainConfig;
this.contractsConfig = options.contractsConfig; this.contractsConfig = options.contractsConfig;
this.logger = options.logger; this.logger = options.logger;
this.fs = options.fs;
} }
/*eslint complexity: ["error", 25]*/ /*eslint complexity: ["error", 25]*/
@ -44,7 +44,7 @@ class Simulator {
let simulatorAccounts = this.blockchainConfig.simulatorAccounts || options.simulatorAccounts; let simulatorAccounts = this.blockchainConfig.simulatorAccounts || options.simulatorAccounts;
if (simulatorAccounts && simulatorAccounts.length > 0) { if (simulatorAccounts && simulatorAccounts.length > 0) {
let web3 = new (require('web3'))(); let web3 = new (require('web3'))();
let parsedAccounts = AccountParser.parseAccountsConfig(simulatorAccounts, web3, fs.dappPath(), this.logger); let parsedAccounts = AccountParser.parseAccountsConfig(simulatorAccounts, web3, this.fs.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);
@ -68,7 +68,7 @@ class Simulator {
} }
runCommand(cmds, useProxy, host, port) { runCommand(cmds, useProxy, host, port) {
const ganache_main = require.resolve('ganache-cli', {paths: [fs.embarkPath('node_modules')]}); const ganache_main = require.resolve('ganache-cli', {paths: [this.fs.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);
const ganache_bin = require(ganache_json).bin; const ganache_bin = require(ganache_json).bin;
@ -86,7 +86,7 @@ class Simulator {
shelljs.exec(`node ${program} ${cmds.join(' ')}`, {async : true}); shelljs.exec(`node ${program} ${cmds.join(' ')}`, {async : true});
if(useProxy){ if(useProxy){
let ipcObject = new IPC({ipcRole: 'client', fs}); let ipcObject = new IPC({ipcRole: 'client', fs: this.fs});
if (this.blockchainConfig.wsRPC) { if (this.blockchainConfig.wsRPC) {
return new Proxy(ipcObject).serve(host, port, true, this.blockchainConfig.wsOrigins, []); return new Proxy(ipcObject).serve(host, port, true, this.blockchainConfig.wsOrigins, []);
} }
@ -95,5 +95,3 @@ class Simulator {
} }
} }
} }
module.exports = Simulator;

View File

@ -0,0 +1,58 @@
export function pingEndpoint(host, port, type, protocol, origin, callback) {
// remove any extra information from a host string, e.g. port, path, query
const _host = require("url").parse(
// url.parse() expects a protocol segment else it won't parse as desired
host.slice(0, 4) === "http" ? host : `${protocol}://${host}`
).hostname;
let closed = false;
const close = (req, closeMethod) => {
if (!closed) {
closed = true;
req[closeMethod]();
}
};
const handleEvent = (req, closeMethod, ...args) => {
close(req, closeMethod);
setImmediate(() => { callback(...args); });
};
const handleError = (req, closeMethod) => {
req.on("error", (err) => {
if (err.code !== "ECONNREFUSED") {
console.error(
`Ping: Network error` +
(err.message ? ` '${err.message}'` : "") +
(err.code ? ` (code: ${err.code})` : "")
);
}
// when closed additional error events will not callback
if (!closed) { handleEvent(req, closeMethod, err); }
});
};
const handleSuccess = (req, closeMethod, event) => {
req.once(event, () => {
handleEvent(req, closeMethod);
});
};
const handleRequest = (req, closeMethod, event) => {
handleError(req, closeMethod);
handleSuccess(req, closeMethod, event);
};
if (type === "ws") {
const url = `${protocol === "https" ? "wss" : "ws"}://${_host}:${port}/`;
const req = new (require("ws"))(url, origin ? {origin} : {});
handleRequest(req, "close", "open");
} else {
const headers = origin ? {Origin: origin} : {};
const req = (protocol === "https" ? require("https") : require("http")).get(
{headers, host: _host, port}
);
handleRequest(req, "abort", "response");
}
}

View File

@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*"]
}

View File

@ -0,0 +1,3 @@
{
"extends": "../../tslint.json"
}

View File

@ -92,6 +92,7 @@
"deep-equal": "1.0.1", "deep-equal": "1.0.1",
"ejs": "2.6.1", "ejs": "2.6.1",
"embark-authenticator": "^4.1.0-beta.0", "embark-authenticator": "^4.1.0-beta.0",
"embark-blockchain-process": "^4.1.0-beta.0",
"embark-api": "^4.1.0-beta.0", "embark-api": "^4.1.0-beta.0",
"embark-blockchain-listener": "^4.1.0-beta.0", "embark-blockchain-listener": "^4.1.0-beta.0",
"embark-code-generator": "^4.1.0-beta.0", "embark-code-generator": "^4.1.0-beta.0",

View File

@ -1,3 +1,4 @@
import { BlockchainClient, Simulator } from 'embark-blockchain-process';
import { __ } from 'embark-i18n'; import { __ } from 'embark-i18n';
let async = require('async'); let async = require('async');
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
@ -34,17 +35,24 @@ class EmbarkController {
blockchain(env, client) { blockchain(env, client) {
this.context = [constants.contexts.blockchain]; this.context = [constants.contexts.blockchain];
return require('../lib/modules/blockchain_process/blockchain.js')(this.config.blockchainConfig, client, env, return BlockchainClient(this.config.blockchainConfig, {
this.config.webServerConfig.certOptions, null, null, this.logger, this.events, true).run(); clientName: client,
env,
certOptions: this.config.webServerConfig.certOptions,
logger: this.logger,
events: this.events,
isStandalone: true,
fs
}).run();
} }
simulator(options) { simulator(options) {
this.context = options.context || [constants.contexts.simulator, constants.contexts.blockchain]; this.context = options.context || [constants.contexts.simulator, constants.contexts.blockchain];
let Simulator = require('../lib/modules/blockchain_process/simulator.js');
let simulator = new Simulator({ let simulator = new Simulator({
blockchainConfig: this.config.blockchainConfig, blockchainConfig: this.config.blockchainConfig,
contractsConfig: this.config.contractsConfig, contractsConfig: this.config.contractsConfig,
logger: this.logger logger: this.logger,
fs
}); });
simulator.run(options); simulator.run(options);
} }

View File

@ -298,7 +298,7 @@ class Engine {
} }
web3Service(options) { web3Service(options) {
this.registerModule('blockchain_process', { this.registerModulePackage('embark-blockchain-process', {
client: this.client, client: this.client,
locale: this.locale, locale: this.locale,
isDev: this.isDev, isDev: this.isDev,

View File

@ -108,6 +108,11 @@ Plugin.prototype.loadPlugin = function() {
}; };
Plugin.prototype.loadInternalPlugin = function() { Plugin.prototype.loadInternalPlugin = function() {
if (utils.isEs6Module(this.pluginModule)) {
if (this.pluginModule.default) {
this.pluginModule = this.pluginModule.default;
}
}
new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/ new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/
}; };

View File

@ -68,64 +68,6 @@ function getJson(url, cb) {
httpGetJson(url, cb); httpGetJson(url, cb);
} }
function pingEndpoint(host, port, type, protocol, origin, callback) {
// remove any extra information from a host string, e.g. port, path, query
const _host = require('url').parse(
// url.parse() expects a protocol segment else it won't parse as desired
host.slice(0, 4) === 'http' ? host : `${protocol}://${host}`
).hostname;
let closed = false;
const close = (req, closeMethod) => {
if (!closed) {
closed = true;
req[closeMethod]();
}
};
const handleEvent = (req, closeMethod, ...args) => {
close(req, closeMethod);
setImmediate(() => { callback(...args); });
};
const handleError = (req, closeMethod) => {
req.on('error', (err) => {
if (err.code !== 'ECONNREFUSED') {
console.error(
`Ping: Network error` +
(err.message ? ` '${err.message}'` : '') +
(err.code ? ` (code: ${err.code})` : '')
);
}
// when closed additional error events will not callback
if (!closed) { handleEvent(req, closeMethod, err); }
});
};
const handleSuccess = (req, closeMethod, event) => {
req.once(event, () => {
handleEvent(req, closeMethod);
});
};
const handleRequest = (req, closeMethod, event) => {
handleError(req, closeMethod);
handleSuccess(req, closeMethod, event);
};
if (type === 'ws') {
const url = `${protocol === 'https' ? 'wss' : 'ws'}://${_host}:${port}/`;
const req = new (require('ws'))(url, origin ? {origin} : {});
handleRequest(req, 'close', 'open');
} else {
const headers = origin ? {Origin: origin} : {};
const req = (protocol === 'https' ? require('https') : require('http')).get(
{headers, host: _host, port}
);
handleRequest(req, 'abort', 'response');
}
}
function cd(folder) { function cd(folder) {
const shelljs = require('shelljs'); const shelljs = require('shelljs');
shelljs.cd(folder); shelljs.cd(folder);
@ -385,7 +327,6 @@ module.exports = {
httpsGetJson, httpsGetJson,
getJson, getJson,
isValidDomain, isValidDomain,
pingEndpoint,
cd, cd,
sed, sed,
downloadFile, downloadFile,

View File

@ -1,5 +1,5 @@
/*globals describe, it*/ /*globals describe, it*/
const Blockchain = require('../lib/modules/blockchain_process/blockchain.js'); import { BlockchainClient } from 'embark-blockchain-process';
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
import {defaultHost} from 'embark-utils'; import {defaultHost} from 'embark-utils';
const path = require('path'); const path = require('path');
@ -13,7 +13,7 @@ describe('embark.Blockchain', function() {
describe('with empty config', function() { describe('with empty config', function() {
it('should have a default config', function(done) { it('should have a default config', function(done) {
const blockchain = new Blockchain({}); const blockchain = new BlockchainClient({}, { fs });
const expectedConfig = { const expectedConfig = {
networkType: 'custom', networkType: 'custom',
genesisBlock: false, genesisBlock: false,
@ -93,7 +93,7 @@ describe('embark.Blockchain', function() {
} }
] ]
}; };
let blockchain = new Blockchain(config); let blockchain = new BlockchainClient(config, { fs });
let expectedConfig = { let expectedConfig = {
networkType: 'livenet', networkType: 'livenet',

View File

@ -5,7 +5,7 @@ const {
const sinon = require('sinon'); const sinon = require('sinon');
import { IPC } from 'embark-core'; import { IPC } from 'embark-core';
let fs = require('../lib/core/fs'); let fs = require('../lib/core/fs');
let Proxy = require('../lib/modules/blockchain_process/proxy'); const { Proxy } = require('embark-blockchain-process');
const constants = require('embark-core/constants'); const constants = require('embark-core/constants');
describe('embark.Proxy', function () { describe('embark.Proxy', function () {