Code coverage report for ethereum.js/lib/web3/ip.js

Statements: 75.32% (58 / 77)      Branches: 53.85% (14 / 26)      Functions: 64.29% (9 / 14)      Lines: 75.32% (58 / 77)      Ignored: none     

All files » ethereum.js/lib/web3/ » ip.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213                                                  2 2   2     2 5 5 5   5   5   5         5           5     2   2     2           2       2 1 1                       2 2       2             2     2     2   2 2                                 2 2   2 2     2                   2 1 1   1 1               2                             2 3     3 2   3     2   1 1     1 1   1   1 1         1             2   1 1     1 1     2    
/*
    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 ipcprovider.js
 * @authors:
 *   Fabian Vogelsteller <fabian@ethdev.com>
 * @date 2015
 */
 
"use strict";
 
//var web3 = require('../web3');
var errors = require('./errors');
var utils = require('../utils/utils');
 
var errorTimeout = '{"jsonrpc": "2.0", "error": {"code": -32603, "message": "IPC Request timed out for method  \'__method__\'"}, "id": "__id__"}';
 
 
var IpcProvider = function (path, net) {
    var _this = this;
    this.responseCallbacks = {};
    this.path = path;
    
    net = net || require('net');
 
    this.connection = net.connect({path: this.path});
 
    this.connection.on('error', function(e){
        console.error('IPC Connection Error', e);
        _this._timeout();
    });
 
    this.connection.on('end', function(){
        _this._timeout();
    }); 
 
 
    // LISTEN FOR CONNECTION RESPONSES
    this.connection.on('data', function(data) {
        /*jshint maxcomplexity: 6 */
 
        _this._parseResponse(data.toString()).forEach(function(result){
 
            var id = null;
 
            // get the id which matches the returned id
            Iif(utils.isArray(result)) {
                result.forEach(function(load){
                    if(_this.responseCallbacks[load.id])
                        id = load.id;
                });
            } else {
                id = result.id;
            }
 
            // fire the callback
            if(_this.responseCallbacks[id]) {
                _this.responseCallbacks[id](null, result);
                delete _this.responseCallbacks[id];
            }
        });
    });
};
 
/**
Will parse the response and make an array out of it.
 
@method _parseResponse
@param {String} data
*/
IpcProvider.prototype._parseResponse = function(data) {
    var _this = this,
        returnValues = [];
    
    // DE-CHUNKER
    var dechunkedData = data
        .replace(/\}\{/g,'}|--|{') // }{
        .replace(/\}\]\[\{/g,'}]|--|[{') // }][{
        .replace(/\}\[\{/g,'}|--|[{') // }[{
        .replace(/\}\]\{/g,'}]|--|{') // }]{
        .split('|--|');
 
    dechunkedData.forEach(function(data){
 
        // prepend the last chunk
        Iif(_this.lastChunk)
            data = _this.lastChunk + data;
 
        var result = null;
 
        try {
            result = JSON.parse(data);
 
        } catch(e) {
 
            _this.lastChunk = data;
 
            // start timeout to cancel all requests
            clearTimeout(_this.lastChunkTimeout);
            _this.lastChunkTimeout = setTimeout(function(){
                _this.timeout();
                throw errors.InvalidResponse(data);
            }, 1000 * 15);
 
            return;
        }
 
        // cancel timeout and set chunk to null
        clearTimeout(_this.lastChunkTimeout);
        _this.lastChunk = null;
 
        Eif(result)
            returnValues.push(result);
    });
 
    return returnValues;
};
 
 
/**
Get the adds a callback to the responseCallbacks object,
which will be called if a response matching the response Id will arrive.
 
@method _addResponseCallback
*/
IpcProvider.prototype._addResponseCallback = function(payload, callback) {
    var id = payload.id || payload[0].id;
    var method = payload.method || payload[0].method;
 
    this.responseCallbacks[id] = callback;
    this.responseCallbacks[id].method = method;
};
 
/**
Timeout all requests when the end/error event is fired
 
@method _timeout
*/
IpcProvider.prototype._timeout = function() {
    for(var key in this.responseCallbacks) {
        if(this.responseCallbacks.hasOwnProperty(key)){
            this.responseCallbacks[key](errorTimeout.replace('__id__', key).replace('__method__', this.responseCallbacks[key].method));
            delete this.responseCallbacks[key];
        }
    }
};
 
 
/**
Check if the current connection is still valid.
 
@method isConnected
*/
IpcProvider.prototype.isConnected = function() {
    var _this = this;
 
    // try reconnect, when connection is gone
    if(!_this.connection.writable)
        _this.connection.connect({path: _this.path});
 
    return !!this.connection.writable;
};
 
IpcProvider.prototype.send = function (payload) {
 
    Eif(this.connection.writeSync) {
        var result;
 
        // try reconnect, when connection is gone
        Eif(!this.connection.writable)
            this.connection.connect({path: this.path});
 
        var data = this.connection.writeSync(JSON.stringify(payload));
 
        try {
            result = JSON.parse(data);
        } catch(e) {
            throw errors.InvalidResponse(data);                
        }
 
        return result;
 
    } else {
        throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.');
    }
};
 
IpcProvider.prototype.sendAsync = function (payload, callback) {
    // try reconnect, when connection is gone
    Eif(!this.connection.writable)
        this.connection.connect({path: this.path});
 
 
    this.connection.write(JSON.stringify(payload));
    this._addResponseCallback(payload, callback);
};
 
module.exports = IpcProvider;