move blockchain connection code to its own module

This commit is contained in:
Iuri Matias 2018-07-27 16:54:33 -04:00
parent b2bf717728
commit 45cc43bfc8
4 changed files with 205 additions and 349 deletions

View File

@ -1,296 +0,0 @@
const Web3 = require('web3');
const async = require('async');
const Provider = require('./provider.js');
const utils = require('../utils/utils');
const WEB3_READY = 'web3Ready';
class Blockchain {
constructor(options) {
const self = this;
this.plugins = options.plugins;
this.logger = options.logger;
this.events = options.events;
this.contractsConfig = options.contractsConfig;
this.blockchainConfig = options.blockchainConfig;
this.web3 = options.web3;
this.isDev = options.isDev;
this.web3Endpoint = '';
this.isWeb3Ready = false;
this.web3StartedInProcess = false;
self.events.setCommandHandler("blockchain:web3:isReady", (cb) => {
console.dir("geting state of web3");
console.dir(self.isWeb3Ready.toString());
cb(self.isWeb3Ready);
});
if (!this.web3) {
this.initWeb3();
} else {
this.isWeb3Ready = true;
}
this.registerServiceCheck();
this.registerRequests();
this.registerWeb3Object();
this.registerEvents();
}
initWeb3() {
const self = this;
this.web3 = new Web3();
if (this.contractsConfig.deployment.type !== "rpc" && this.contractsConfig.deployment.type !== "ws") {
const message = __("contracts config error: unknown deployment type %s", this.contractsConfig.deployment.type);
this.logger.error(message);
//return cb(message);
}
const protocol = (this.contractsConfig.deployment.type === "rpc") ? this.contractsConfig.deployment.protocol : 'ws';
this.web3Endpoint = utils.buildUrl(protocol, this.contractsConfig.deployment.host, this.contractsConfig.deployment.port);//`${protocol}://${this.contractsConfig.deployment.host}:${this.contractsConfig.deployment.port}`;
const providerOptions = {
web3: this.web3,
accountsConfig: this.contractsConfig.deployment.accounts,
blockchainConfig: this.blockchainConfig,
logger: this.logger,
isDev: this.isDev,
type: this.contractsConfig.deployment.type,
web3Endpoint: self.web3Endpoint
};
this.provider = new Provider(providerOptions);
self.events.request("processes:launch", "blockchain", () => {
console.dir("======> blockchain launched!");
console.dir("starting web3 provider");
self.provider.startWeb3Provider(() => {
console.dir("funding accounts");
self.provider.fundAccounts(() => {
console.dir("registering web3 object");
self.isWeb3Ready = true;
self.events.emit(WEB3_READY);
self.registerWeb3Object();
//self.events.emit("check:backOnline:Ethereum");
});
});
});
}
registerEvents() {
//const self = this;
//self.events.on('check:wentOffline:Ethereum', () => {
// self.logger.trace('Ethereum went offline: stopping web3 provider...');
// self.provider.stop();
// // once the node goes back online, we can restart the provider
// self.events.once('check:backOnline:Ethereum', () => {
// self.logger.trace('Ethereum back online: starting web3 provider...');
// self.provider.startWeb3Provider(() => {
// self.logger.trace('web3 provider restarted after ethereum node came back online');
// });
// });
//});
}
onReady(callback) {
console.dir("======> onReady!!");
console.dir("this.isWeb3Ready: " + this.isWeb3Ready.toString());
if (this.isWeb3Ready) {
return callback();
}
this.events.once(WEB3_READY, () => {
console.dir("got event triggered");
callback();
});
}
registerServiceCheck() {
const self = this;
const NO_NODE = 'noNode';
this.events.request("services:register", 'Ethereum', function (cb) {
async.waterfall([
function checkNodeConnection(next) {
if (!self.web3.currentProvider) {
return next(NO_NODE, {name: "No Blockchain node found", status: 'off'});
}
next();
},
function checkVersion(next) {
// TODO: web3_clientVersion method is currently not implemented in web3.js 1.0
self.web3._requestManager.send({method: 'web3_clientVersion', params: []}, (err, version) => {
if (err) {
self.isWeb3Ready = false;
return next(null, {name: "Ethereum node (version unknown)", status: 'on'});
}
if (version.indexOf("/") < 0) {
self.events.emit(WEB3_READY);
self.isWeb3Ready = true;
return next(null, {name: version, status: 'on'});
}
let nodeName = version.split("/")[0];
let versionNumber = version.split("/")[1].split("-")[0];
let name = nodeName + " " + versionNumber + " (Ethereum)";
self.events.emit(WEB3_READY);
self.isWeb3Ready = true;
return next(null, {name: name, status: 'on'});
});
}
], (err, statusObj) => {
if (err && err !== NO_NODE) {
return cb(err);
}
console.dir(statusObj);
cb(statusObj);
});
}, 5000, 'off');
}
registerRequests() {
const self = this;
this.events.setCommandHandler("blockchain:defaultAccount:get", function(cb) {
cb(self.defaultAccount());
});
this.events.setCommandHandler("blockchain:defaultAccount:set", function(account, cb) {
self.setDefaultAccount(account);
cb();
});
this.events.setCommandHandler("blockchain:block:byNumber", function(blockNumber, cb) {
self.getBlock(blockNumber, cb);
});
this.events.setCommandHandler("blockchain:gasPrice", function(cb) {
self.getGasPrice(cb);
});
this.events.setCommandHandler("blockchain:contract:create", function(params, cb) {
cb(self.ContractObject(params));
});
}
defaultAccount() {
return this.web3.eth.defaultAccount;
}
setDefaultAccount(account) {
this.web3.eth.defaultAccount = account;
}
getAccounts(cb) {
this.web3.eth.getAccounts(cb);
}
getCode(address, cb) {
this.web3.eth.getCode(address, cb);
}
getBlock(blockNumber, cb) {
this.web3.eth.getBlock(blockNumber, cb);
}
getGasPrice(cb) {
console.dir("geting gas price");
const self = this;
this.onReady(() => {
console.dir("it's ready, getting gas price");
self.web3.eth.getGasPrice(cb);
});
}
ContractObject(params) {
return new this.web3.eth.Contract(params.abi, params.address);
}
deployContractObject(contractObject, params) {
return contractObject.deploy({arguments: params.arguments, data: params.data});
}
estimateDeployContractGas(deployObject, cb) {
return deployObject.estimateGas().then((gasValue) => {
cb(null, gasValue);
}).catch(cb);
}
deployContractFromObject(deployContractObject, params, cb) {
const self = this;
let hash;
let calledBacked = false;
function callback(err, receipt) {
if (calledBacked) {
return;
}
if (!err && !receipt.contractAddress) {
return; // Not deployed yet. Need to wait
}
if (interval) {
clearInterval(interval);
}
calledBacked = true;
cb(err, receipt);
}
// This interval is there to compensate for the event that sometimes doesn't get triggered when using WebSocket
// FIXME The issue somehow only happens when the blockchain node is started in the same terminal
const interval = setInterval(() => {
if (!hash) {
return; // Wait until we receive the hash
}
self.web3.eth.getTransactionReceipt(hash, (err, receipt) => {
if (!err && !receipt) {
return; // Transaction is not yet complete
}
callback(err, receipt);
});
}, 500);
deployContractObject.send({
from: params.from, gas: params.gas, gasPrice: params.gasPrice
}, function (err, transactionHash) {
if (err) {
return callback(err);
}
hash = transactionHash;
}).on('receipt', function (receipt) {
if (receipt.contractAddress !== undefined) {
callback(null, receipt);
}
}).then(function (_contract) {
if (!hash) {
return; // Somehow we didn't get the receipt yet... Interval will catch it
}
self.web3.eth.getTransactionReceipt(hash, callback);
}).catch(callback);
}
determineDefaultAccount(cb) {
const self = this;
self.getAccounts(function (err, accounts) {
if (err) {
self.logger.error(err);
return cb(new Error(err));
}
let accountConfig = self.blockchainConfig.account;
let selectedAccount = accountConfig && accountConfig.address;
self.setDefaultAccount(selectedAccount || accounts[0]);
cb();
});
}
registerWeb3Object() {
// doesn't feel quite right, should be a cmd or plugin method
// can just be a command without a callback
this.events.emit("runcode:register", "web3", this.web3);
}
}
module.exports = Blockchain;

View File

@ -1,34 +1,28 @@
const Web3 = require('web3');
const async = require('async');
const Provider = require('./provider.js');
const utils = require('../../utils/utils');
const constants = require('../../constants');
const embarkJsUtils = require('embarkjs').Utils;
const utils = require('../utils/utils');
const WEB3_READY = 'web3Ready';
// TODO: consider another name, this is the blockchain connector
class BlockchainConnector {
constructor(embark, options) {
class Blockchain {
constructor(options) {
const self = this;
this.plugins = options.plugins;
this.logger = embark.logger;
this.events = embark.events;
this.contractsConfig = embark.config.contractsConfig;
this.blockchainConfig = embark.config.blockchainConfig;
this.logger = options.logger;
this.events = options.events;
this.contractsConfig = options.contractsConfig;
this.blockchainConfig = options.blockchainConfig;
this.web3 = options.web3;
this.isDev = options.isDev;
this.web3Endpoint = '';
this.isWeb3Ready = false;
this.web3StartedInProcess = false;
self.events.setCommandHandler("blockchain:web3:isReady", (cb) => {
cb(self.isWeb3Ready);
});
self.events.setCommandHandler("blockchain:object", (cb) => {
cb(self);
});
if (!this.web3) {
this.initWeb3();
} else {
@ -38,19 +32,9 @@ class BlockchainConnector {
this.registerRequests();
this.registerWeb3Object();
this.registerEvents();
this.subscribeToPendingTransactions();
}
//initWeb3() {
initWeb3(cb) {
if (!cb) {
cb = function(){};
}
if (this.isWeb3Ready) {
this.events.emit(WEB3_READY);
return cb();
}
initWeb3() {
const self = this;
this.web3 = new Web3();
@ -232,14 +216,60 @@ class BlockchainConnector {
}
deployContractFromObject(deployContractObject, params, cb) {
embarkJsUtils.secureSend(this.web3, deployContractObject, {
const self = this;
let hash;
let calledBacked = false;
function callback(err, receipt) {
if (calledBacked) {
return;
}
if (!err && !receipt.contractAddress) {
return; // Not deployed yet. Need to wait
}
if (interval) {
clearInterval(interval);
}
calledBacked = true;
cb(err, receipt);
}
// This interval is there to compensate for the event that sometimes doesn't get triggered when using WebSocket
// FIXME The issue somehow only happens when the blockchain node is started in the same terminal
const interval = setInterval(() => {
if (!hash) {
return; // Wait until we receive the hash
}
self.web3.eth.getTransactionReceipt(hash, (err, receipt) => {
if (!err && !receipt) {
return; // Transaction is not yet complete
}
callback(err, receipt);
});
}, 500);
deployContractObject.send({
from: params.from, gas: params.gas, gasPrice: params.gasPrice
}, true, cb);
}, function (err, transactionHash) {
if (err) {
return callback(err);
}
hash = transactionHash;
}).on('receipt', function (receipt) {
if (receipt.contractAddress !== undefined) {
callback(null, receipt);
}
}).then(function (_contract) {
if (!hash) {
return; // Somehow we didn't get the receipt yet... Interval will catch it
}
self.web3.eth.getTransactionReceipt(hash, callback);
}).catch(callback);
}
determineDefaultAccount(cb) {
const self = this;
self.getAccounts(function(err, accounts) {
self.getAccounts(function (err, accounts) {
if (err) {
self.logger.error(err);
return cb(new Error(err));
@ -256,21 +286,7 @@ class BlockchainConnector {
// can just be a command without a callback
this.events.emit("runcode:register", "web3", this.web3, false);
}
subscribeToPendingTransactions() {
const self = this;
this.onReady(() => {
if (self.logsSubscription) {
self.logsSubscription.unsubscribe();
}
self.logsSubscription = self.web3.eth
.subscribe('newBlockHeaders', () => {})
.on("data", function (blockHeader) {
self.events.emit('block:header', blockHeader);
});
});
}
}
module.exports = BlockchainConnector;
module.exports = Blockchain;

View File

@ -11,13 +11,17 @@ class Provider {
this.web3Endpoint = options.web3Endpoint;
this.logger = options.logger;
this.isDev = options.isDev;
this.engine = new ProviderEngine();
this.asyncMethods = {};
}
startWeb3Provider(callback) {
const self = this;
if (this.type === 'rpc') {
self.provider = new this.web3.providers.HttpProvider(self.web3Endpoint);
self.engine.addProvider(new RpcSubprovider({
rpcUrl: self.web3Endpoint
}));
} else if (this.type === 'ws') {
self.provider = new this.web3.providers.WebsocketProvider(self.web3Endpoint, {headers: {Origin: "embark"}});
self.provider.on('error', e => self.logger.error('Websocket Error', e));
@ -26,7 +30,25 @@ class Provider {
return callback(__("contracts config error: unknown deployment type %s", this.type));
}
self.web3.setProvider(self.provider);
// network connectivity error
self.engine.on('error', (err) => {
// report connectivity errors
self.logger.error(err);
});
self.engine.start();
//self.on('error', (err) => {
// console.log('ERR', JSON.stringify(err));
// // report connectivity errors as trace due to polling
// self.logger.trace('web3 provider error: ', err);
// self.logger.trace('stopping web3 provider due to error');
// // prevent continuous polling errors
// self.stop();
//});
//self.web3.setProvider(self);
//self.start();
self.accounts = AccountParser.parseAccountsConfig(self.accountsConfig, self.web3, self.logger);
self.addresses = [];
@ -38,16 +60,22 @@ class Provider {
self.addresses.push(account.address);
self.web3.eth.accounts.wallet.add(account);
});
self.web3.eth.defaultAccount = self.addresses[0];
const realSend = self.provider.send.bind(self.provider);
self.provider.send = function (payload, cb) {
if (payload.method === 'eth_accounts') {
return realSend(payload, function (err, result) {
self.realAccountFunction = self.web3.eth.getAccounts;
self.web3.eth.getAccounts = function (cb) {
if (!cb) {
cb = function () {
};
}
return new Promise((resolve, reject) => {
self.realAccountFunction((err, accounts) => {
if (err) {
return cb(err);
}
result.result = result.result.concat(self.addresses);
cb(null, result);
accounts = accounts.concat(self.addresses);
// accounts = self.addresses.concat(accounts);
cb(null, accounts);
resolve(accounts);
});
}
realSend(payload, cb);
@ -75,10 +103,36 @@ class Provider {
if (!self.isDev) {
return callback();
}
async.eachLimit(self.accounts, 1, (account, eachCb) => {
async.each(self.accounts, (account, eachCb) => {
fundAccount(self.web3, account.address, account.hexBalance, eachCb);
}, callback);
}
stop() {
this.engine.stop();
}
eth_accounts(payload, cb) {
return cb(null, this.addresses);
}
sendAsync(payload, callback) {
let method = this.asyncMethods[payload.method];
if (method) {
return method.call(method, payload, (err, result) => {
if (err) {
return callback(err);
}
let response = {'id': payload.id, 'jsonrpc': '2.0', 'result': result};
callback(null, response);
});
}
this.engine.sendAsync.apply(this.engine, arguments);
}
send() {
return this.engine.send.apply(this.engine, arguments);
}
}
module.exports = Provider;

View File

@ -0,0 +1,82 @@
const async = require('async');
const AccountParser = require('../../utils/accountParser');
const fundAccount = require('./fundAccount');
class Provider {
constructor(options) {
this.web3 = options.web3;
this.accountsConfig = options.accountsConfig;
this.blockchainConfig = options.blockchainConfig;
this.type = options.type;
this.web3Endpoint = options.web3Endpoint;
this.logger = options.logger;
this.isDev = options.isDev;
}
startWeb3Provider(callback) {
const self = this;
if (this.type === 'rpc') {
self.provider = new this.web3.providers.HttpProvider(self.web3Endpoint);
} else if (this.type === 'ws') {
self.provider = new this.web3.providers.WebsocketProvider(self.web3Endpoint, {headers: {Origin: "embark"}});
} else {
return callback(__("contracts config error: unknown deployment type %s", this.type));
}
self.web3.setProvider(self.provider);
self.accounts = AccountParser.parseAccountsConfig(self.accountsConfig, self.web3, self.logger);
self.addresses = [];
if (!self.accounts.length) {
return callback();
}
self.accounts.forEach(account => {
self.addresses.push(account.address);
self.web3.eth.accounts.wallet.add(account);
});
self.web3.eth.defaultAccount = self.addresses[0];
const realSend = self.provider.send.bind(self.provider);
self.provider.send = function (payload, cb) {
if (payload.method === 'eth_accounts') {
return realSend(payload, function (err, result) {
if (err) {
return cb(err);
}
result.result = result.result.concat(self.addresses);
cb(null, result);
});
}
realSend(payload, cb);
};
callback();
}
stop() {
if (this.provider && this.provider.removeAllListeners) {
this.provider.removeAllListeners('connect');
this.provider.removeAllListeners('error');
this.provider.removeAllListeners('end');
this.provider.removeAllListeners('data');
this.provider.responseCallbacks = {};
this.provider = null;
}
}
fundAccounts(callback) {
const self = this;
if (!self.accounts.length) {
return callback();
}
if (!self.isDev) {
return callback();
}
async.eachLimit(self.accounts, 1, (account, eachCb) => {
fundAccount(self.web3, account.address, account.hexBalance, eachCb);
}, callback);
}
}
module.exports = Provider;