Merge pull request #8 from debris/autoprovider

Autoprovider
This commit is contained in:
Marian OANCΞA 2014-11-11 17:20:53 +02:00
commit d85cef557b
11 changed files with 660 additions and 520 deletions

12
dist/ethereum.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -3,7 +3,7 @@
<head> <head>
<script type="text/javascript" src="js/es6-promise/promise.min.js"></script> <script type="text/javascript" src="js/es6-promise/promise.min.js"></script>
<script type="text/javascript" src="../dist/ethereum.min.js"></script> <script type="text/javascript" src="../dist/ethereum.js"></script>
<script type="text/javascript"> <script type="text/javascript">
if (window.Promise === undefined) { if (window.Promise === undefined) {
@ -13,8 +13,9 @@ if (window.Promise === undefined) {
var web3 = require('web3'); var web3 = require('web3');
//web3.setProvider(new web3.providers.QtProvider()); //web3.setProvider(new web3.providers.QtProvider());
web3.setProvider(new web3.providers.HttpRpcProvider("http://localhost:8080")); //web3.setProvider(new web3.providers.HttpRpcProvider("http://localhost:8080"));
// web3.setProvider(new web3.providers.WebSocketProvider("ws://localhost:40404/eth")); // web3.setProvider(new web3.providers.WebSocketProvider("ws://localhost:40404/eth"));
web3.setProvider(new web3.providers.AutoProvider());
function testSnippet() { function testSnippet() {
web3.eth.watch({altered: web3.eth.coinbase}).changed(function() { web3.eth.watch({altered: web3.eth.coinbase}).changed(function() {

View File

@ -25,8 +25,8 @@ var build = function(src, dst) {
detectGlobals: false, detectGlobals: false,
bundleExternal: false bundleExternal: false
}) })
.add('./')
.require('./' + src + '.js', {expose: 'web3'}) .require('./' + src + '.js', {expose: 'web3'})
.add('./' + src + '.js')
.transform('envify', { .transform('envify', {
NODE_ENV: 'build' NODE_ENV: 'build'
}) })
@ -50,6 +50,25 @@ var build = function(src, dst) {
.pipe(gulp.dest( DEST )); .pipe(gulp.dest( DEST ));
}; };
var buildDev = function(src, dst) {
return browserify({
debug: true,
insert_global_vars: false,
detectGlobals: false,
bundleExternal: false
})
.require('./' + src + '.js', {expose: 'web3'})
.add('./' + src + '.js')
.transform('envify', {
NODE_ENV: 'build'
})
.transform('unreachable-branch-transform')
.bundle()
.pipe(exorcist(path.join( DEST, dst + '.js.map')))
.pipe(source(dst + '.js'))
.pipe(gulp.dest( DEST ));
};
var uglifyFile = function(file) { var uglifyFile = function(file) {
return gulp.src( DEST + file + '.js') return gulp.src( DEST + file + '.js')
.pipe(uglify()) .pipe(uglify())
@ -79,7 +98,11 @@ gulp.task('build', ['clean'], function () {
}); });
gulp.task('buildQt', ['clean'], function () { gulp.task('buildQt', ['clean'], function () {
return build('index_qt', 'ethereum_qt'); return build('index_qt', 'ethereum');
});
gulp.task('buildDev', ['clean'], function () {
return buildDev('index', 'ethereum');
}); });
gulp.task('uglify', ['build'], function(){ gulp.task('uglify', ['build'], function(){
@ -87,7 +110,7 @@ gulp.task('uglify', ['build'], function(){
}); });
gulp.task('uglifyQt', ['buildQt'], function () { gulp.task('uglifyQt', ['buildQt'], function () {
return uglifyFile('ethereum_qt'); return uglifyFile('ethereum');
}); });
gulp.task('watch', function() { gulp.task('watch', function() {
@ -96,3 +119,5 @@ gulp.task('watch', function() {
gulp.task('default', ['bower', 'lint', 'build', 'uglify']); gulp.task('default', ['bower', 'lint', 'build', 'uglify']);
gulp.task('qt', ['bower', 'lint', 'buildQt', 'uglifyQt']); gulp.task('qt', ['bower', 'lint', 'buildQt', 'uglifyQt']);
gulp.task('dev', ['bower', 'lint', 'buildDev']);

View File

@ -2,5 +2,6 @@ var web3 = require('./lib/main');
web3.providers.WebSocketProvider = require('./lib/websocket'); web3.providers.WebSocketProvider = require('./lib/websocket');
web3.providers.HttpRpcProvider = require('./lib/httprpc'); web3.providers.HttpRpcProvider = require('./lib/httprpc');
web3.providers.QtProvider = require('./lib/qt'); web3.providers.QtProvider = require('./lib/qt');
web3.providers.AutoProvider = require('./lib/autoprovider');
module.exports = web3; module.exports = web3;

103
lib/autoprovider.js Normal file
View File

@ -0,0 +1,103 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file websocket.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* @date 2014
*/
/*
* @brief if qt object is available, uses QtProvider,
* if not tries to connect over websockets
* if it fails, it uses HttpRpcProvider
*/
if (process.env.NODE_ENV !== 'build') {
var WebSocket = require('ws'); // jshint ignore:line
}
if (process.env.NODE_ENV !== 'build') {
var web3 = require('./web3'); // jshint ignore:line
}
var AutoProvider = function (userOptions) {
if (web3.haveProvider()) {
return;
}
// before we determine what provider we are, we have to cache request
this.sendQueue = [];
this.onmessageQueue = [];
if (navigator.qt) {
this.provider = new web3.providers.QtProvider();
return;
}
userOptions = userOptions || {};
var options = {
httprpc: userOptions.httprpc || 'http://localhost:8080',
websockets: userOptions.websockets || 'ws://localhost:40404/eth'
};
var self = this;
var closeWithSuccess = function (success) {
ws.close();
if (success) {
self.provider = new web3.providers.WebSocketProvider(options.websockets);
return;
}
self.provider = new web3.providers.HttpRpcProvider(options.httprpc);
self.poll = self.provider.poll.bind(self.provider);
self.sendQueue.forEach(function (payload) {
self.provider(payload);
});
self.onmessageQueue.forEach(function (handler) {
self.provider.onmessage = handler;
});
};
var ws = new WebSocket(options.websockets);
ws.onopen = function() {
closeWithSuccess(true);
};
ws.onerror = function() {
closeWithSuccess(false);
};
};
AutoProvider.prototype.send = function (payload) {
if (this.provider) {
this.provider.send(payload);
return;
}
this.sendQueue.push(payload);
};
Object.defineProperty(AutoProvider.prototype, 'onmessage', {
set: function (handler) {
if (this.provider) {
this.provider.onmessage = handler;
return;
}
this.onmessageQueue.push(handler);
}
});
module.exports = AutoProvider;

View File

@ -21,26 +21,25 @@
* @date 2014 * @date 2014
*/ */
if(process.env.NODE_ENV !== "build") { if (process.env.NODE_ENV !== "build") {
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line
} }
var HttpRpcProvider = function (host) {
var HttpRpcProvider = function (host) {
this.handlers = []; this.handlers = [];
this.host = host; this.host = host;
}; };
function formatJsonRpcObject(object) { function formatJsonRpcObject(object) {
return { return {
jsonrpc: '2.0', jsonrpc: '2.0',
method: object.call, method: object.call,
params: object.args, params: object.args,
id: object._id id: object._id
}; };
} }
function formatJsonRpcMessage(message) { function formatJsonRpcMessage(message) {
var object = JSON.parse(message); var object = JSON.parse(message);
return { return {
@ -48,9 +47,9 @@ if(process.env.NODE_ENV !== "build") {
data: object.result, data: object.result,
error: object.error error: object.error
}; };
} }
HttpRpcProvider.prototype.sendRequest = function (payload, cb) { HttpRpcProvider.prototype.sendRequest = function (payload, cb) {
var data = formatJsonRpcObject(payload); var data = formatJsonRpcObject(payload);
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
@ -61,18 +60,18 @@ if(process.env.NODE_ENV !== "build") {
cb(request); cb(request);
} }
}; };
}; };
HttpRpcProvider.prototype.send = function (payload) { HttpRpcProvider.prototype.send = function (payload) {
var self = this; var self = this;
this.sendRequest(payload, function (request) { this.sendRequest(payload, function (request) {
self.handlers.forEach(function (handler) { self.handlers.forEach(function (handler) {
handler.call(self, formatJsonRpcMessage(request.responseText)); handler.call(self, formatJsonRpcMessage(request.responseText));
}); });
}); });
}; };
HttpRpcProvider.prototype.poll = function (payload, id) { HttpRpcProvider.prototype.poll = function (payload, id) {
var self = this; var self = this;
this.sendRequest(payload, function (request) { this.sendRequest(payload, function (request) {
var parsed = JSON.parse(request.responseText); var parsed = JSON.parse(request.responseText);
@ -83,12 +82,12 @@ if(process.env.NODE_ENV !== "build") {
handler.call(self, {_event: payload.call, _id: id, data: parsed.result}); handler.call(self, {_event: payload.call, _id: id, data: parsed.result});
}); });
}); });
}; };
Object.defineProperty(HttpRpcProvider.prototype, "onmessage", { Object.defineProperty(HttpRpcProvider.prototype, "onmessage", {
set: function (handler) { set: function (handler) {
this.handlers.push(handler); this.handlers.push(handler);
} }
}); });
module.exports = HttpRpcProvider; module.exports = HttpRpcProvider;

View File

@ -22,7 +22,7 @@
* @date 2014 * @date 2014
*/ */
function flattenPromise (obj) { function flattenPromise (obj) {
if (obj instanceof Promise) { if (obj instanceof Promise) {
return Promise.resolve(obj); return Promise.resolve(obj);
} }
@ -59,9 +59,9 @@
} }
return Promise.resolve(obj); return Promise.resolve(obj);
} }
var ethMethods = function () { var ethMethods = function () {
var blockCall = function (args) { var blockCall = function (args) {
return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber"; return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber";
}; };
@ -88,9 +88,9 @@
{ name: 'lll', call: 'eth_lll' } { name: 'lll', call: 'eth_lll' }
]; ];
return methods; return methods;
}; };
var ethProperties = function () { var ethProperties = function () {
return [ return [
{ name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' }, { name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' },
{ name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' }, { name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' },
@ -102,18 +102,18 @@
{ name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' }, { name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' },
{ name: 'number', getter: 'eth_number'} { name: 'number', getter: 'eth_number'}
]; ];
}; };
var dbMethods = function () { var dbMethods = function () {
return [ return [
{ name: 'put', call: 'db_put' }, { name: 'put', call: 'db_put' },
{ name: 'get', call: 'db_get' }, { name: 'get', call: 'db_get' },
{ name: 'putString', call: 'db_putString' }, { name: 'putString', call: 'db_putString' },
{ name: 'getString', call: 'db_getString' } { name: 'getString', call: 'db_getString' }
]; ];
}; };
var shhMethods = function () { var shhMethods = function () {
return [ return [
{ name: 'post', call: 'shh_post' }, { name: 'post', call: 'shh_post' },
{ name: 'newIdentity', call: 'shh_newIdentity' }, { name: 'newIdentity', call: 'shh_newIdentity' },
@ -121,9 +121,9 @@
{ name: 'newGroup', call: 'shh_newGroup' }, { name: 'newGroup', call: 'shh_newGroup' },
{ name: 'addToGroup', call: 'shh_addToGroup' } { name: 'addToGroup', call: 'shh_addToGroup' }
]; ];
}; };
var ethWatchMethods = function () { var ethWatchMethods = function () {
var newFilter = function (args) { var newFilter = function (args) {
return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter'; return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter';
}; };
@ -133,17 +133,17 @@
{ name: 'uninstallFilter', call: 'eth_uninstallFilter' }, { name: 'uninstallFilter', call: 'eth_uninstallFilter' },
{ name: 'getMessages', call: 'eth_getMessages' } { name: 'getMessages', call: 'eth_getMessages' }
]; ];
}; };
var shhWatchMethods = function () { var shhWatchMethods = function () {
return [ return [
{ name: 'newFilter', call: 'shh_newFilter' }, { name: 'newFilter', call: 'shh_newFilter' },
{ name: 'uninstallFilter', call: 'shh_uninstallFilter' }, { name: 'uninstallFilter', call: 'shh_uninstallFilter' },
{ name: 'getMessage', call: 'shh_getMessages' } { name: 'getMessage', call: 'shh_getMessages' }
]; ];
}; };
var setupMethods = function (obj, methods) { var setupMethods = function (obj, methods) {
methods.forEach(function (method) { methods.forEach(function (method) {
obj[method.name] = function () { obj[method.name] = function () {
return flattenPromise(Array.prototype.slice.call(arguments)).then(function (args) { return flattenPromise(Array.prototype.slice.call(arguments)).then(function (args) {
@ -164,9 +164,9 @@
}); });
}; };
}); });
}; };
var setupProperties = function (obj, properties) { var setupProperties = function (obj, properties) {
properties.forEach(function (property) { properties.forEach(function (property) {
var proto = {}; var proto = {};
proto.get = function () { proto.get = function () {
@ -199,9 +199,9 @@
} }
Object.defineProperty(obj, property.name, proto); Object.defineProperty(obj, property.name, proto);
}); });
}; };
var web3 = { var web3 = {
_callbacks: {}, _callbacks: {},
_events: {}, _events: {},
providers: {}, providers: {},
@ -288,24 +288,24 @@
var cb = callbacks[id]; var cb = callbacks[id];
cb(data); cb(data);
} }
}; };
var eth = web3.eth; var eth = web3.eth;
setupMethods(eth, ethMethods()); setupMethods(eth, ethMethods());
setupProperties(eth, ethProperties()); setupProperties(eth, ethProperties());
setupMethods(web3.db, dbMethods()); setupMethods(web3.db, dbMethods());
setupMethods(web3.shh, shhMethods()); setupMethods(web3.shh, shhMethods());
var ethWatch = { var ethWatch = {
changed: 'eth_changed' changed: 'eth_changed'
}; };
setupMethods(ethWatch, ethWatchMethods()); setupMethods(ethWatch, ethWatchMethods());
var shhWatch = { var shhWatch = {
changed: 'shh_changed' changed: 'shh_changed'
}; };
setupMethods(shhWatch, shhWatchMethods()); setupMethods(shhWatch, shhWatchMethods());
var ProviderManager = function() { var ProviderManager = function() {
this.queued = []; this.queued = [];
this.polls = []; this.polls = [];
this.ready = false; this.ready = false;
@ -324,9 +324,9 @@
setTimeout(poll, 12000); setTimeout(poll, 12000);
}; };
poll(); poll();
}; };
ProviderManager.prototype.send = function(data, cb) { ProviderManager.prototype.send = function(data, cb) {
data._id = this.id; data._id = this.id;
if (cb) { if (cb) {
web3._callbacks[data._id] = cb; web3._callbacks[data._id] = cb;
@ -341,53 +341,57 @@
console.warn("provider is not set"); console.warn("provider is not set");
this.queued.push(data); this.queued.push(data);
} }
}; };
ProviderManager.prototype.set = function(provider) { ProviderManager.prototype.set = function(provider) {
if(this.provider !== undefined && this.provider.unload !== undefined) { if(this.provider !== undefined && this.provider.unload !== undefined) {
this.provider.unload(); this.provider.unload();
} }
this.provider = provider; this.provider = provider;
this.ready = true; this.ready = true;
}; };
ProviderManager.prototype.sendQueued = function() { ProviderManager.prototype.sendQueued = function() {
for(var i = 0; this.queued.length; i++) { for(var i = 0; this.queued.length; i++) {
// Resend // Resend
this.send(this.queued[i]); this.send(this.queued[i]);
} }
}; };
ProviderManager.prototype.installed = function() { ProviderManager.prototype.installed = function() {
return this.provider !== undefined; return this.provider !== undefined;
}; };
ProviderManager.prototype.startPolling = function (data, pollId) { ProviderManager.prototype.startPolling = function (data, pollId) {
if (!this.provider || !this.provider.poll) { if (!this.provider || !this.provider.poll) {
return; return;
} }
this.polls.push({data: data, id: pollId}); this.polls.push({data: data, id: pollId});
}; };
ProviderManager.prototype.stopPolling = function (pollId) { ProviderManager.prototype.stopPolling = function (pollId) {
for (var i = this.polls.length; i--;) { for (var i = this.polls.length; i--;) {
var poll = this.polls[i]; var poll = this.polls[i];
if (poll.id === pollId) { if (poll.id === pollId) {
this.polls.splice(i, 1); this.polls.splice(i, 1);
} }
} }
}; };
web3.provider = new ProviderManager(); web3.provider = new ProviderManager();
web3.setProvider = function(provider) { web3.setProvider = function(provider) {
provider.onmessage = messageHandler; provider.onmessage = messageHandler;
web3.provider.set(provider); web3.provider.set(provider);
web3.provider.sendQueued(); web3.provider.sendQueued();
}; };
var Filter = function(options, impl) { web3.haveProvider = function() {
return !!web3.provider.provider;
};
var Filter = function(options, impl) {
this.impl = impl; this.impl = impl;
this.callbacks = []; this.callbacks = [];
@ -398,42 +402,42 @@
web3.on(impl.changed, id, self.trigger.bind(self)); web3.on(impl.changed, id, self.trigger.bind(self));
web3.provider.startPolling({call: impl.changed, args: [id]}, id); web3.provider.startPolling({call: impl.changed, args: [id]}, id);
}); });
}; };
Filter.prototype.arrived = function(callback) { Filter.prototype.arrived = function(callback) {
this.changed(callback); this.changed(callback);
}; };
Filter.prototype.changed = function(callback) { Filter.prototype.changed = function(callback) {
var self = this; var self = this;
this.promise.then(function(id) { this.promise.then(function(id) {
self.callbacks.push(callback); self.callbacks.push(callback);
}); });
}; };
Filter.prototype.trigger = function(messages) { Filter.prototype.trigger = function(messages) {
for(var i = 0; i < this.callbacks.length; i++) { for(var i = 0; i < this.callbacks.length; i++) {
this.callbacks[i].call(this, messages); this.callbacks[i].call(this, messages);
} }
}; };
Filter.prototype.uninstall = function() { Filter.prototype.uninstall = function() {
var self = this; var self = this;
this.promise.then(function (id) { this.promise.then(function (id) {
self.impl.uninstallFilter(id); self.impl.uninstallFilter(id);
web3.provider.stopPolling(id); web3.provider.stopPolling(id);
web3.off(impl.changed, id); web3.off(impl.changed, id);
}); });
}; };
Filter.prototype.messages = function() { Filter.prototype.messages = function() {
var self = this; var self = this;
return this.promise.then(function (id) { return this.promise.then(function (id) {
return self.impl.getMessages(id); return self.impl.getMessages(id);
}); });
}; };
function messageHandler(data) { function messageHandler(data) {
if(data._event !== undefined) { if(data._event !== undefined) {
web3.trigger(data._event, data._id, data.data); web3.trigger(data._event, data._id, data.data);
return; return;
@ -446,7 +450,7 @@
delete web3._callbacks[data._id]; delete web3._callbacks[data._id];
} }
} }
} }
module.exports = web3; module.exports = web3;

View File

@ -16,11 +16,12 @@
*/ */
/** @file qt.js /** @file qt.js
* @authors: * @authors:
* Jeffrey Wilcke <jeff@ethdev.com>
* Marek Kotewicz <marek@ethdev.com> * Marek Kotewicz <marek@ethdev.com>
* @date 2014 * @date 2014
*/ */
var QtProvider = function() { var QtProvider = function() {
this.handlers = []; this.handlers = [];
var self = this; var self = this;
@ -29,16 +30,16 @@
handler.call(self, JSON.parse(message.data)); handler.call(self, JSON.parse(message.data));
}); });
}; };
}; };
QtProvider.prototype.send = function(payload) { QtProvider.prototype.send = function(payload) {
navigator.qt.postMessage(JSON.stringify(payload)); navigator.qt.postMessage(JSON.stringify(payload));
}; };
Object.defineProperty(QtProvider.prototype, "onmessage", { Object.defineProperty(QtProvider.prototype, "onmessage", {
set: function(handler) { set: function(handler) {
this.handlers.push(handler); this.handlers.push(handler);
} }
}); });
module.exports = QtProvider; module.exports = QtProvider;

View File

@ -16,16 +16,17 @@
*/ */
/** @file websocket.js /** @file websocket.js
* @authors: * @authors:
* Jeffrey Wilcke <jeff@ethdev.com>
* Marek Kotewicz <marek@ethdev.com> * Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com> * Marian Oancea <marian@ethdev.com>
* @date 2014 * @date 2014
*/ */
if(process.env.NODE_ENV !== "build") { if (process.env.NODE_ENV !== "build") {
var WebSocket = require('ws'); // jshint ignore:line var WebSocket = require('ws'); // jshint ignore:line
} }
var WebSocketProvider = function(host) { var WebSocketProvider = function(host) {
// onmessage handlers // onmessage handlers
this.handlers = []; this.handlers = [];
// queue will be filled with messages if send is invoked before the ws is ready // queue will be filled with messages if send is invoked before the ws is ready
@ -49,8 +50,9 @@ if(process.env.NODE_ENV !== "build") {
self.send(self.queued[i]); self.send(self.queued[i]);
} }
}; };
}; };
WebSocketProvider.prototype.send = function(payload) {
WebSocketProvider.prototype.send = function(payload) {
if(this.ready) { if(this.ready) {
var data = JSON.stringify(payload); var data = JSON.stringify(payload);
@ -58,17 +60,17 @@ if(process.env.NODE_ENV !== "build") {
} else { } else {
this.queued.push(payload); this.queued.push(payload);
} }
}; };
WebSocketProvider.prototype.onMessage = function(handler) { WebSocketProvider.prototype.onMessage = function(handler) {
this.handlers.push(handler); this.handlers.push(handler);
}; };
WebSocketProvider.prototype.unload = function() { WebSocketProvider.prototype.unload = function() {
this.ws.close(); this.ws.close();
}; };
Object.defineProperty(WebSocketProvider.prototype, "onmessage", { Object.defineProperty(WebSocketProvider.prototype, "onmessage", {
set: function(provider) { this.onMessage(provider); } set: function(provider) { this.onMessage(provider); }
}); });
module.exports = WebSocketProvider; module.exports = WebSocketProvider;