WMCC Core RPC
@alias module:http.RPC
@constructor
@param {Node} node
541857
function RPC(node) {
  if (!(this instanceof RPC))
    return new RPC(node);

  RPCBase.call(this);

  assert(node, 'RPC requires a Node.');

  this.node = node;
  this.network = node.network;
  this.workers = node.workers;
  this.chain = node.chain;
  this.mempool = node.mempool;
  this.pool = node.pool;
  this.fees = node.fees;
  this.miner = node.miner;
  this.logger = node.logger.context('rpc');

  this.mining = false;
  this.procLimit = 0;
  this.attempt = null;
  this.lastActivity = 0;
  this.boundChain = false;
  this.nonce1 = 0;
  this.nonce2 = 0;
  this.merkleMap = new Map();
  this.pollers = [];

  this.init();
}
196407
function amqpSenderNode(config) {

        RED.nodes.createNode(this, config);

        // get endpoint configuration
        this.endpoint = RED.nodes.getNode(config.endpoint);
        // get all other configuration
        this.address = config.address;
        this.autosettle = config.autosettle;
        this.dynamic = config.dynamic;
        this.sndsettlemode = config.sndsettlemode;
        this.rcvsettlemode = config.rcvsettlemode;
        this.durable = config.durable;
        this.expirypolicy = config.expirypolicy;

        var node = this;
        // node not yet connected
        this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });

        if (node.endpoint) {

            node.endpoint.connect(function(connection) {
                setup(connection);
            });

            /**
             * Node setup for creating sender link
             *
             * @param connection    Connection instance
             */
            function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build sender options based on node configuration
                var options = {
                    target: {
                        address: node.address,
                        dynamic: node.dynamic,
                        durable: node.durable,
                        expiry_policy: node.expirypolicy
                    },
                    autosettle: node.autosettle,
                    snd_settle_mode: node.sndsettlemode,
                    rcv_settle_mode: node.rcvsettlemode
                };
                node.sender = node.connection.open_sender(options);

                node.sender.on('accepted', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('released', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.sender.on('rejected', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {
                        node.sender.send(msg.payload);
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    node.connection.close();
                });
            }

        }
    }
832209
function RpcChannel(connection) {
    if (!connection) {
        var msg = 'The connection is mandatory!';
        logger.error(msg);
        throw new TypeError(msg);
    }
    this._connection = connection;
    this._open = true;
    this._queue = [];
    var self = this;
    setInterval(function () {
        executor.call(self);
    }, 100).unref();
}
1062458
function NodeClient(node) {
  if (!(this instanceof NodeClient))
    return new NodeClient(node);

  AsyncObject.call(this);

  this.node = node;
  this.network = node.network;
  this.filter = null;
  this.listen = false;

  this._init();
}
1046081
function RPC(wdb) {
  if (!(this instanceof RPC))
    return new RPC(wdb);

  RPCBase.call(this);

  assert(wdb, 'RPC requires a WalletDB.');

  this.wdb = wdb;
  this.network = wdb.network;
  this.logger = wdb.logger.context('rpc');
  this.client = wdb.client;

  this.wallet = null;

  this.init();
}
56545
function amqpEndpointNode(n) {

        RED.nodes.createNode(this, n);

        // save node parameters
        this.host = n.host;
        this.port = n.port;
        this.username = n.username;
        this.password = n.password;
        this.container_id = n.container_id;
        this.rejectUnauthorized = n.rejectUnauthorized;
        this.usetls = n.usetls;

        if (this.usetls && n.tls) {
            this.tls = RED.nodes.getNode(n.tls)
        }

        // build options for connection
        var options = { host: this.host, port: this.port};
        if (this.username) {
            options.username = this.username;
        }
        if (this.password) {
            options.password = this.password;
        }
        if (this.container_id) {
            options.container_id = this.container_id;
        } else {
            options.container_id = "node-red-rhea-" + container.generate_uuid();
        }
        if (this.usetls && n.tls) {
            options.transport = 'tls';
            if (this.tls.credentials.cadata) {
                options.ca = this.tls.credentials.cadata
            }
        }

        options.rejectUnauthorized = this.rejectUnauthorized;

        var node = this;

        this.connected = false;
        this.connecting = false;
        
        /**
         * Exposed function for connecting to the remote AMQP container
         * creating an AMQP connection object
         *
         * @param callback  function called when the connection is established
         */
        this.connect = function(callback) {

            // AMQP connection not established, trying to do that
            if (!node.connected && !node.connecting) {

                node.connecting = true;

                node.connection = container.connect(options);

                node.connection.on('connection_error', function(context) {

                    node.connecting = false;
                    node.connected = false;
                    var error = context.connection.get_error();
                    node.error(error);

                });

                node.connection.on('connection_open', function(context) {

                    node.connecting = false;
                    node.connected = true;

                    callback(context.connection);
                });

                node.connection.on('disconnected', function(context) {

                    node.connected = false;
                });

            // AMQP connection already established
            } else {

                callback(node.connection);
            }

        }
    }
1026012
function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build receiver options based on node configuration
                var options = {
                    source: {
                        address: node.address,
                        dynamic: node.dynamic,
                        durable: node.durable,
                        expiry_policy: node.expirypolicy
                     },
                    credit_window: node.creditwindow,
                    autoaccept: node.autoaccept,
                    snd_settle_mode: node.sndsettlemode,
                    rcv_settle_mode: node.rcvsettlemode
                };

                node.receiver = node.connection.open_receiver(options);

                node.receiver.on('message', function(context) {
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    if (msg.credit) {
                        node.receiver.flow(msg.credit);
                    }
                });

                node.on('close', function() {
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                });
            }
1332171
static <T extends RemoteRunnable> T runOnH2ONode(H2ONode node, T runnable) {
    if (node == H2O.SELF) {
      // run directly
      runnable.run();
      return runnable;
    } else {
      RunnableWrapperTask<T> task = new RunnableWrapperTask<>(runnable);
      try {
        return new RPC<>(node, task).call().get()._runnable;
      } catch (DistributedException e) {
        Log.trace("Exception in calling runnable on a remote node",  e);
        Throwable cause = e.getCause();
        throw cause instanceof RuntimeException ? (RuntimeException) cause : e;
      }
    }
  }
1112577
function rdRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    const index = Math.floor(Math.random() * servers.length);
    utils.invokeCallback(cb, null, servers[index]);
}
4432
function report(node) {
            context.report({ node, messageId: "unexpected", data: { operator: node.operator } });
        }
474906
function SlackRtmIn(n) {
    RED.nodes.createNode(this, n);

    var node = this;
    this.client = n.client;
    this.events = n.events;
    this.clientNode = RED.nodes.getNode(this.client);

    var eventNames;
    if (this.events) {
      eventNames = this.events
        .replace(/[\s]+/g, "")
        .split(",")
        .filter(Boolean);
    }

    node.status(statuses.disconnected);

    if (node.client) {
      SetConfigNodeConnectionListeners(node);

      node.clientNode.rtmClient.on("slack_event", (eventType, event) => {
        /**
         * responses to websocket commands come over the without an eventType
         */
        if (eventType === undefined) {
          eventType = "ws_response";
          event.type = eventType;
        }

        /**
         * ignore non-subscribed events
         * 
         * Since the message events are bound to the same object as connection
         * events this feature has been implemented in this fashion vs directly
         * subscribing to prevent stupid (ie: someone setting a value of
         * 'connected' or the like) in node properties. Crude but effective.
         * 
         * It also decouples the feature from the semantics of the client.
         */
        if (this.events && eventNames.length > 0) {
          if (
            !(
              eventNames.includes(event.type) ||
              (event.subtype &&
                eventNames.includes(`${event.type}::${event.subtype}`))
            )
          ) {
            return null;
          }
        }

        /**
         * pong: triggered in response to a ping keep-alive
         *
         * hello: triggered on connect
         *
         * ws_response: triggered after data has been sent over the ws
         *
         * channel_marked: triggered when the bot user has 'read' a channel
         *
         * desktop_notification: triggered when the bot user is @mentioned or
         * otherwise would receive an alert
         *
         * pretty sure nobody is interested in the below
         * note that ws_response is sent on the output side of the output node
         * so receiving it here is double processing
         */
        if (eventType == "pong" || eventType == "ws_response") {
          return null;
        }

        SlackDebug("slack-rtm-in incoming event", event);
        var msg = {};
        msg.payload = node.clientNode.dressResponseMessage(event);
        msg.slackState = node.clientNode.state;
        node.send(msg);
      });
    } else {
      node.status(statuses.misconfigured);
    }
  }
1348465
function laRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    const actives = [];
    if (!client.laParam) {
        client.laParam = {};
    }
    if (client.laParam[serverType]) {
        for (let j = 0; j < servers.length; j++) {
            let count = client.laParam[serverType][servers[j]];
            if (!count) {
                count = 0;
                client.laParam[servers[j]] = 0;
            }
            actives.push(count);
        }
    } else {
        client.laParam[serverType] = {};
        for (let i = 0; i < servers.length; i++) {
            client.laParam[serverType][servers[i]] = 0;
            actives.push(0);
        }
    }
    let rs = [];
    let minInvoke = Number.MAX_VALUE;
    for (let k = 0; k < actives.length; k++) {
        if (actives[k] < minInvoke) {
            minInvoke = actives[k];
            rs = [];
            rs.push(servers[k]);
        } else if (actives[k] === minInvoke) {
            rs.push(servers[k]);
        }
    }
    const index = Math.floor(Math.random() * rs.length);
    const serverId = rs[index];
    client.laParam[serverType][serverId] += 1;
    utils.invokeCallback(cb, null, serverId);
}
541343
function RPCClient(options) {
  if (!(this instanceof RPCClient))
    return new RPCClient(options);

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { uri: options };

  this.options = options;
  this.network = Network.get(options.network);

  this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
  this.apiKey = options.apiKey;
  this.id = 0;
}
685544
function nodeGlobalRequire(file) {
  vm.runInThisContext.call(global, fs.readFileSync(file), file);
}
870785
function MCS(transport, recvOpCode, sendOpCode) {
	this.transport = transport;
	this.recvOpCode = recvOpCode;
	this.sendOpCode = sendOpCode;
	this.channels = [{id : Channel.MCS_GLOBAL_CHANNEL, name : 'global'}];
	this.channels.find = function(callback) {
		for(var i in this) {
			if(callback(this[i])) return this[i];
		};
	};
	
	// bind events
	var self = this;
	this.transport.on('close', function () {
		self.emit('close');
	}).on('error', function (err) {
		self.emit('error', err);
	});
}
449933
function onConnection(socket) {
  var endpoint = new http2.Endpoint(log, 'SERVER', {});
  endpoint.pipe(socket).pipe(endpoint);

  endpoint.on('stream', function(stream) {
    stream.on('headers', function(headers) {
      var path = headers[':path'];
      var filename = join(__dirname, path);

      // Serving server.js from cache. Useful for microbenchmarks.
      if (path == cachedUrl) {
        stream.headers({ ':status': 200 });
        stream.end(cachedFile);
      }

      // Reading file from disk if it exists and is safe.
      else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) {
        stream.headers({ ':status': 200 });

        // If they download the certificate, push the private key too, they might need it.
        if (path === '/localhost.crt') {
          var push = stream.promise({
            ':method': 'GET',
            ':scheme': headers[':scheme'],
            ':authority': headers[':authority'],
            ':path': '/localhost.key'
          });
          push.headers({ ':status': 200 });
          read(join(__dirname, '/localhost.key')).pipe(push);
        }

        read(filename).pipe(stream);
      }

      // Otherwise responding with 404.
      else {
        stream.headers({ ':status': 404 });
        stream.end();
      }
    });
  });
}
652299
function amqpRequesterNode(config) {

        RED.nodes.createNode(this, config);

        //var container = rhea.create_container();

        // get endpoint configuration
        this.endpoint = RED.nodes.getNode(config.endpoint);
        // get all other configuration
        this.address = config.address;

        var node = this;
        // node not yet connected
        this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });

        if (this.endpoint) {

            node.endpoint.connect(function(connection) {
                setup(connection);
            });

            /**
             * Node setup for creating sender link for sending the request
             * and the dynamic receiver for receiving reply
             *
             * @param connection    Connection instance
             */
            function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build sender options based on node configuration
                var sender_options = {
                    target: {
                        address: node.address
                    }
                };
                node.sender = node.connection.open_sender(sender_options);

                node.sender.on('accepted', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send([msg, ]);
                });

                node.sender.on('released', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send([msg, ]);
                });

                node.sender.on('rejected', function(context) {
                    var msg = outDelivery(node, context.delivery);
                    node.send([msg, ]);
                });

                // build receiver options
                var receiver_options = {
                    source: {
                        dynamic: true
                    }
                };
                node.receiver = node.connection.open_receiver(receiver_options);

                node.receiver.on('message', function(context) {
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send([ ,msg]);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {

                        if (node.receiver.source.address) {
                            node.sender.send({ reply_to: node.receiver.source.address, body: msg.payload.body });
                        }

                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                })
            }

        }
    }