Members
(constant) _APIFunctions :Object
Enumerated functions found in the API directory as specified in
rpc_options
.
Type:
- Object
config
Properties:
Name | Type | Description |
---|---|---|
config |
Object | Dynamic configuration options loaded at runtime. |
(constant) configFile
Properties:
Name | Type | Default | Description |
---|---|---|---|
configFile |
String | "./config.json" | Location of JSON data file to load and parse into the config object. May be either a filesystem path or a URL. |
gateways
Properties:
Name | Type | Description |
---|---|---|
gateways |
Gateways | A reference to the gateways manager instance. |
hostEnv
Properties:
Name | Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
hostEnv |
Object | An object containing data and references supplied by the host
environment if the server is running as an embedded component in a
desktop (Electron) environment. Refer to the embedding (parent) script for details
on supplied properties and types.
Properties
|
http_server
Properties:
Name | Type | Description |
---|---|---|
http_server |
httpserv | The default HTTP endpoint. |
(constant) JSONRPC_ERRORS
Defines all standard and application-specific JSON-RPC 2.0 error codes. Standard error codes are in the range -32700 to -32603 while application-specific
error codes are in the range -32001 to -32099. Error codes in the range -32768 to -32000 are reserved for future use.
Properties:
Name | Type | Default | Description |
---|---|---|---|
PARSE_ERROR |
Number | -32700 | Invalid JSON was received (the request cannot be parsed). |
REQUEST_ERROR |
Number | -32600 | The request is not a valid JSON-RPC 2.0 request. |
METHOD_NOT_FOUND_ERROR |
Number | -32601 | The requested RPC method does not exist. |
INVALID_PARAMS_ERROR |
Number | -32602 | The parameters supplied for the requested RPC method are invalid. |
INTERNAL_ERROR |
Number | -32603 | There was an internal server error when attempting to process the RPC request. |
SESSION_CLOSE |
Number | -32001 | The session is about to terminate and any current tokens / credentials will no longer be accepted. |
WRONG_TRANSPORT |
Number | -32002 | The wrong transport was used to deliver API request (e.g. used "http" or "https" instead of "ws" or "wss"). |
ACTION_DISALLOWED |
Number | -32003 | The action being requested is not currently allowed. |
PLAYER_ACTION_ERROR |
Number | -32005 | A player has committed a penalizable wrong or incorrect action. |
(constant) namespace
Properties:
Name | Type | Description |
---|---|---|
namespace |
Object | A global object containing references and data shared by API scripts. |
rpc_options
The default options for the RPC server.
Properties:
Name | Type | Default | Description |
---|---|---|---|
api_dir |
String | "./api" | A directory containing all available API methods that may be invoked. Each API method must match a filename and the entry function in that file must also have the same name. |
http_port |
Number | 8080 | The default listening port for the HTTP server. This value may be overriden by a config setting. |
ws_port |
Number | 8090 | The listening port for the WebSocket server. This value may be overriden by a config setting. |
max_batch_requests |
Number | 5 | The maximum allowable number of batched RPC calls in a single request. If more than this number of calls are encountered in a request batch a JSONRPC_INTERNAL_ERROR error is thrown. |
http_headers |
HTTP_Headers_Array | Default headers to include in HTTP / HTTPS responses. Each array element is an object containing a name / value pair. | |
exposed_api_objects |
Exposed_API_Objects | Internal server references to expose to external API functions. Note that each internal reference may be assigned an alias instead of its actual name. | |
api_timelimit |
Number | 3000 | The time limit, in milliseconds, to allow external API functions to execute. |
http_only_handshake |
Boolean | false | Defines whether session handshakes are done only through HTTP/HTTPS (true), or if they can be done through the WebSocket server (false). |
max_ws_per_ip |
Number | 10 | The maximum number of concurrent WebSocket connections to allow from a single IP. |
exposed_library_objects |
Exposed_Library_Objects | Internal server references to expose to libraries, adapters, communication gateways functions, and other server add-ons. Note that each internal reference may be assigned an alias instead of its actual name. |
(constant) ws_ping_interval :Number
The number of milliseconds to ping connected
WebSockets at in order to keep them alive.
Type:
- Number
ws_ping_intervalID
Properties:
Name | Type | Description |
---|---|---|
ws_ping_intervalID |
Number | The interval ID of the WebSocket server ping / keep-alive timer. |
ws_server
Properties:
Name | Type | Description |
---|---|---|
ws_server |
wsserv | The default WebSocket endpoint. |
Methods
addPendingCashout(fromAccount, toAddress, type, network, amount, fees)
Adds a pending cashout transaction to the
namespace.cp.pendingCashouts
array.
Parameters:
Name | Type | Description |
---|---|---|
fromAccount |
String | The account address that is cashing out. |
toAddress |
String | The address to which the funds are being sent. |
type |
String | The cryptocurrency type associated with the transaction (e.g. "bitcoin"). |
network |
String | The cryptocurrency sub-network associated with the transaction (e.g. "main" or "test3"). |
amount |
String | The amount of the transaction in the smallest denomination for the associated cryptocurrency. |
fees |
String | Any miner fee(s) for the transaction in the smallest denomination for the associated cryptocurrency. |
- Source:
adjustEnvironment()
Adjusts various settings and properties based on the detected runtime environment. For example,
Zeit (NOW) deployments require only a single WebSocket connection that must be on port 80 (this
may change).
allSessions(activeOnlyopt) → {Array}
Returns an array of all currently registered and (optionally) active sesssions
being handled by the server.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
activeOnly |
Boolean |
<optional> |
true | If true, only live or active sessions (i.e. those that have successfully established a handshake and connected), are returned, otherwise all registered (but not necessarily connected), sessions are returned. |
- Source:
Returns:
A list of all registered and (optionally) active sessions currently
being handled by the server.
- Type
- Array
buildCPMessage(messageType) → {Object}
Builds a valid CypherPoker.JS message object (usually included as the
data
property of a JSON-RPC 2.0 result object).
Parameters:
Name | Type | Description |
---|---|---|
messageType |
String | The notification message type to build. |
- Source:
Returns:
A valid CypherPoker.JS message object. Additional properties
to include with the message may be appended directly to this object.
- Type
- Object
buildJSONRPC(versionopt, isResultopt, includeUniqueIDopt)
Builds a JSON-RPC message object.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
version |
String |
<optional> |
"2.0" | The JSON-RPC version to designate the object as. Currently only JSON-RPC 2.0 message formatting is supported and other versions will throw an error. If this parameter is null, the default value is assumed. |
isResult |
Boolean |
<optional> |
true | True if this is a result object or notification, false if it's an error. |
includeUniqueID |
Boolean |
<optional> |
false | A uniquely generated message ID will be generated if true otherwise no ID is included (e.g. notification). |
callAccountDatabase(method, message) → {Promise}
Calls the an account database interface with a method, message, and optional HMAC
signature.
Parameters:
Name | Type | Description |
---|---|---|
method |
String | The adapter or remote (RPC) method to invoke. |
message |
Object | The accompanying data to stringify, (if applicable) sign with
config.CP.API.database.accessKey , and include with
the remote (RPC) or local request. |
- Source:
Returns:
Resolves with the response object returned from the server or
database adapter, or rejects with an error.
- Type
- Promise
cashoutIsPending(fromAccount, type, network) → {Boolean}
Checks if a cashout transaction for a specific account is pending (appears in the
namespace.cp.pendingCashouts
array). Only one pending cashout transaction
per account, cryptocurrency type, and network, is assumed to exist.
Parameters:
Name | Type | Description |
---|---|---|
fromAccount |
String | The account address to check. |
type |
String | The cryptocurrency type associated with the pending transaction (e.g. "bitcoin"). |
network |
String | The cryptocurrency sub-network associated with the pending transaction (e.g. "main" or "test3"). |
- Source:
Returns:
True if the specified account has a transaction pending, false otherwise.
- Type
- Boolean
checkPassword(password, pwhash) → {Boolean}
Compares a password (or any string) against its SHA256 hash.
Parameters:
Name | Type | Description |
---|---|---|
password |
String | The plaintext password (or any string) to compare. |
pwhash |
String | The hex-encoded, SHA256 hash to compare password
against. |
- Source:
Returns:
True if the password matched the supplied hash, false otherwise.
- Type
- Boolean
(async) connectTunnel(connectionObject1, connectionObject2)
Connects two ends of a tunnel by intercepting message sending, receiving, and
socket closure at the WebSocket level.
Parameters:
Name | Type | Description |
---|---|---|
connectionObject1 |
Object | The object containing a socket reference,
private_id , tunnel object, and other information to connect
to connectionObject2 . |
connectionObject2 |
Object | The object containing a socket reference,
private_id , tunnel object, and other information to connect
to connectionObject1 . |
- Source:
(async) disconnectTunnel(connectionObject, remainopt)
Disconnects a single tunnel end, optionally keeping it open for a future
connection.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
connectionObject |
Object | The connection object containing a socket
reference, private_id , tunnel information object,
user_token , server_token , and other information
for the tunneled connection. |
||
remain |
Boolean |
<optional> |
true | If false, the connection will no longer be available for a new connection. A client connection should almost never remain but an endpoint may. |
- Source:
(async) estimateTxFee(txDataopt, priorityopt, APITypeopt, networkopt) → {String}
Returns an estimated miner fee for a transaction. The fee estimation may either be based on an
external service or an internal calculation.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
txData |
* |
<optional> |
null | The transaction for which to estimate the fee. The format
for this parameter differs based on the APIType and possibly network .If omitted, a typical (average) transaction is assumed. For a "bitcoin" APIType , this parameter is expected to be a string of hex-encoded data
comprising the binary transaction. If omitted, the transaction is assumed to be 250 bytes. |
priority |
Number |
<optional> |
1 | The priority with which the transaction is to be posted. A higher-priority
transaction (closer to or equal to 0), is expected to be posted faster than a lower priority one (> 0).
This paramater is dependent on the APIType and possibly the network type.When APIType is "bitcoin", a priority of 0 is the highest priority (to be included in the next 1-2 blocks),
a priority of 1 is a medium priority (3 to 6 blocks), and 2 is a low priority (> 6 blocks). |
APIType |
String |
<optional> |
"bitcoin" | The main cryptocurrency API type. |
network |
String |
<optional> |
null | The cryptocurrency sub-network, if applicable, for the
transaction. Current network types include: "main" and "test3". If null ,
the default network specified in config.CP.API[APIType].default.network is used. |
- Source:
Returns:
The estimated transaction fee, as a numeric string in the lowest denomination of the associated
cryptocurrency (e.g. satoshis if
APIType="bitcoin"
), based on the supplied txData
,
priority
, APIType
, and network
. If any parameter is invalid or unrecognized,
null
is returned.
- Type
- String
(async) getAccount(searchObj) → {Promise}
Searches for and returns the latest details about a specific account.
Parameters:
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
searchObj |
Object | An object specifiying the search parameters. All
included criteria must be met in order for a match.
Properties
|
- Source:
Returns:
The resolved promise contains an array of up to two AccountObject
instances containing the latest activity for the account, index 0 being the most recent, or
null
if no matching account exists. A rejected promise contains an Error
object.
- Type
- Promise
getAddress(walletObj, networkopt, cashAddressopt)
Returns the address of a Bitcoin wallet object.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
walletObj |
Object | A Bitcoin wallet data object. | ||
network |
String |
<optional> |
"main" | The sub-network for which to get the address. Either "main" (default), "test", "regtest", or any common BCH variant of these. |
cashAddress |
Boolean |
<optional> |
false | If true, a Bitcoin Cash address is returned instead of a standard (legacy) Bitcoin Base58 address. |
- Source:
getConfigByPath(configPath, configObjopt) → {*}
Returns a configuration setting from the configuration data such as the
global application config via a do-notation path string (as in
standard JavaScript dot notation).
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
configPath |
String | The path of the object within the configuration object to retrieve. | ||
configObj |
Object |
<optional> |
config | The current configuration object being evaluated. This reference is passed for recursion but may be used to limit the search to specific child objects only. |
Returns:
The first matching configuration object or property, or
null
if
it can't be found.
- Type
- *
getConnectionByAlias(alias) → {Object}
Returns a connection object from
namespace.wss.connections
based on a tunnel alias.
Parameters:
Name | Type | Description |
---|---|---|
alias |
String | The tunnel alias for which to retrieve the connection object. |
- Source:
Returns:
The connection object matching the tunnel alias or
null
if no such connection exists. In the unlikely event that more than one matchibng
connection object exists, only the first one is returned.
- Type
- Object
getConnectionByCID(connectionID, userToken, serverToken) → {Object}
Returns a connection object from
namespace.wss.connections
based on a connection ID.
Parameters:
Name | Type | Description |
---|---|---|
connectionID |
String | The connection ID for which to retrieve the connection object. |
userToken |
String | The user-generated token stored with the specific connection object. |
serverToken |
String | The server-generated token stored with the specific connection object. |
- Source:
Returns:
The connection object matching all parameters, or
null
if no such connection exists. In the unlikely event that more than one matchibng
connection object exists, only the first one is returned.
- Type
- Object
getConnectionByPID(privateID) → {Object}
Returns a connection object from
namespace.wss.connections
based on a private ID.
Parameters:
Name | Type | Description |
---|---|---|
privateID |
String | The private ID for which to retrieve the connection object. |
- Source:
Returns:
The connection object matching the private ID or
null
if no such connection exists. In the unlikely event that more than one matchibng
connection object exists, only the first one is returned.
- Type
- Object
getConnectionBySocket(socket) → {Object}
Returns a connection object from
namespace.wss.connections
based on a socket
instance.
Parameters:
Name | Type | Description |
---|---|---|
socket |
Object | The socket reference to find within the namespace.wss.connections
object. |
- Source:
Returns:
The connection object matching the socket reference or
null
if no such connection exists. In the unlikely event that more than one matchibng
connection object exists, only the first one is returned.
- Type
- Object
getHandler(handlerType, subType, caseSensitiveopt) → {Object}
Retrieves the first availablle handler of a certain type and sub-type from
the config object's
CP.RPC.handlers
array.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
handlerType |
String | The main handler category matching a handler's
type definition. E.g. "cryptocurrency" |
||
subType |
String | The secondary handler category matching one of the handler's
types elements. If this is "any" or "*" then the first match for the
handlerType os returned. |
||
caseSensitive |
Boolean |
<optional> |
false | If true, the sub-type match is done with case sensititivity. |
Returns:
Either the class instance of the found handler, or
null
if no such handler can be found.
- Type
- Object
getPrivateID(sessionObj) → {String}
Returns a private session identifier from given server and user tokens.
Parameters:
Name | Type | Description |
---|---|---|
sessionObj |
Object | A session object such as that generated by a WSS JSON-RPC 2.0
server. No validation is performed on the session object's server_token ,
user_token properties (this should be done prior to invoking this function). |
- Source:
Returns:
The private identifier associated with the established
session, or
null
if no identifier can be found.
- Type
- String
handleHTTPRequest(requestObj, responseObj)
Handles data received through the HTTP endpoint and invokes processRPCRequest when a full request is received via a POST
method. This endpoint may also used to call functionailty through GET requests.
Parameters:
Name | Type | Description |
---|---|---|
requestObj |
Object | HTTP request object https://nodejs.org/api/http.html#http_class_http_incomingmessage |
responseObj |
Object | HTTP response object https://nodejs.org/api/http.html#http_class_http_serverresponse |
handleWebSocketClose(event)
Handles a WebSocket close / disconnect event and notifies all active / live
sessions of the disconnection.
Parameters:
Name | Type | Description |
---|---|---|
event |
Event | A standard WebSocket close event. |
- Source:
handleWSDisconnect()
Function invoked when a single WebSocket connection is closed / disconnected.
handleWSRequest(requestData)
Handles a WebSocket request by creating a session object and invoking
processRPCRequest.
Parameters:
Name | Type | Description |
---|---|---|
requestData |
Object | The raw, unparsed request body. |
handshakeOK(sessionObj) → {Boolean}
Verifies whether a handshake for a specific session has been successfully established.
Parameters:
Name | Type | Description |
---|---|---|
sessionObj |
Object | The session object associated with the incoming request. |
- Source:
Returns:
True if the session specified by the parameter has been successfully
established, false if the information doesn't match a live internal session record.
- Type
- Boolean
heartbeat()
Invoked when a WebSocket client pong is received in response to a ping.
Note that this function is invoked in the context of the responding WebSocket
instance.
invokeAPIFunction(sessionObj, requestNumopt)
Invokes an external API function as requested by a RPC call.
Parameters:
Name | Type | Attributes | Default | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sessionObj |
Object | An object containing data for the current sesssion.
The contents of this object will differ depending on the type of endpoint that received the original request.
Properties
|
|||||||||||||||||
requestNum |
Number |
<optional> |
null | The index of the batched request within sessionObj.requestObj to process if the request is a batched request. If null or omitted then the requests is processed as a single request. |
isExcluded(privateID, excludeopt) → {Boolean}
Checks if a private ID is included in a list of exclusions (such as in
a sendBroadcast call).
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
privateID |
String | The privateID to check. | ||
exclude |
Object |
<optional> |
null | The object containing the exclusion list.
This object must contain a rcp property which is an indexed \
array of recipients being excluded. |
- Source:
Returns:
True if the specific
privateID
was included in the
exclusion list, false otherwise.
- Type
- Boolean
loadAPIFunctions(…postLoadFunctionsopt)
Loads and verifies all API functions in the directory specified in
rpc_options
and optionally invokes one or more functions when completed.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
postLoadFunctions |
function |
<optional> <repeatable> |
Any function(s) to invoke once the API functions have been loaded and verified. |
loadConfig(filePathopt, RPCOptionsopt) → {Promise}
Asynchronously loads and parses an external JSON configuration file, making it available
as the global config object.
Parameters:
Name | Type | Attributes | Default | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
filePath |
String |
<optional> |
configFile | The URL or filesystem path of the
external configuration file to load. If the RPCOptions.host property
is included (the request is being made to a shared hosting environment), this URL
should contain the server IP rather than the domain name. |
||||||||||||||||
RPCOptions |
Object |
<optional> |
null | If the filePath points to a
JSON-RPC 2.0 endpoint, this object contains additional properties to use
for the call.
Properties
|
Returns:
The promise resolves with the loaded and parsed configuration
object and rejects with the error when the file could not be loaded or parsed.
- Type
- Promise
(async) loadHandlers(typeopt)
Loads and starts any handlers defined in the config
object's
CP.RPC.handlers
array. Each affected element
will have a new handler
property addedd to it with the
defined handler instance. Any existing handlers will be destroy
ed
and removed.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
type |
String |
<optional> |
"all" | The handlers or a specific type
to load. If "all", all handlers found in CP.RPC.handlers are
created. |
makeConnectionID(sessionObj) → {String}
Returns a connection identifier based on information provided via an active WebSocket
within a session object.
Parameters:
Name | Type | Description |
---|---|---|
sessionObj |
Object | A session object such as that generated by a WSS JSON-RPC 2.0 server. |
- Source:
Returns:
A connection identifier based on the remote (client) endpoint's
protocol family (IPv4 or IPv6), and IP. The port is omitted since it may change.
- Type
- String
makeConnectionToken() → {String}
Generates a random server connection token to be used for authentication (for example,
to be used as a
server_token
).
- Source:
Returns:
A randomly generated server connection token.
- Type
- String
makePrivateID(sessionObj) → {String}
Creates a private session identifier from given server and user tokens.
Parameters:
Name | Type | Description |
---|---|---|
sessionObj |
Object | A session object such as that generated by a WSS JSON-RPC 2.0
server. No validation is performed on the session object's server_token ,
user_token properties (this should be done prior to invoking this function). |
- Source:
Returns:
The SHA256 hash of the server token concatenated with a semi-colon
and the user token:
SHA256(server_token + ":" + user_token)
. null
is returned if either of the input parameters is invalid.
- Type
- String
mkdirSync(targetDir)
Utility function to recursively create a directory structure. This is a drop-in
replacement function to use when
fs.mkdirSync
with the mkdirSync
option fails (typically when running as an Electron app where the version is < 5.0.0).
Adapted from [https://stackoverflow.com/a/40686853](https://stackoverflow.com/a/40686853).
Parameters:
Name | Type | Description |
---|---|---|
targetDir |
String | The target directory structure to synchronously and recursively create. |
- Source:
- See:
MySQLDateTime(dateObj) → {String}
Generates a MySQL-compatible date/timestamp.
Parameters:
Name | Type | Description |
---|---|---|
dateObj |
Date | The native JavaScript Date object from which to generate the timestamp. |
- Source:
Returns:
A MySQL "TIMESTAMP" field type compatible date/time string.
- Type
- String
noop()
Empty (no operation) function provided as a parameter to the WebSocket ping
function in ping.
onStartHTTPServer()
Function invoked by startHTTPServer when the HTTP server has been successfully started.
onStartWSServer()
Function invoked by startWSServer when the WebSocket server has been successfully started.
(async) onTunnelClose(closedConnObj, otherConnObj, nextListener, closeEvent)
A proxy or intercept function for a standard WebSocket "close" event when
the socket has been closed. The other end of the tunnel is notified and the tunnel
is either completely removed if closed by the endpoint or re-opened if closed
by a client. Typically the "close" handler is swapped into the WebSocket instance in
connectTunnel.
Parameters:
Name | Type | Description |
---|---|---|
closedConnObj |
Object | The tunneled connection that has just closed. |
otherConnObj |
Object | The connection at the other end of the tunnel. |
nextListener |
function | A reference to the next "close" event listener registered in the event chain for the closed socket. |
closeEvent |
Object | The event included in the original "close" dispatch. |
- Source:
(async) onTunnelMessage(connectionSourceObj, connectionDestObj, message)
A proxy or intercept function for a standard WebSocket "message" event when
the socket is being tunneled that automatically forwards the receiving data to
the other end of the tunnel.
Typically this handler is swapped into the WebSocket instance in connectTunnel where the extra parameter is introduced.
Typically this handler is swapped into the WebSocket instance in connectTunnel where the extra parameter is introduced.
Parameters:
Name | Type | Description |
---|---|---|
connectionSourceObj |
Object | The tunneled sending connection object containing a
socket reference, private_id , tunnel information
object, tunnelServerMessages , and other information for the tunneled
connection. |
connectionDestObj |
Object | The tunneled receiving connection object containing a
socket reference, private_id , tunnel information
object, tunnelServerMessages , and other information for the tunneled
connection. |
message |
* | The message received from connectionSourceObj to send
to connectionDestObj . |
- Source:
onWSConnection(wsInstance, request)
Invoked when a WebSocket connection is established on the WebSocket server.
Parameters:
Name | Type | Description |
---|---|---|
wsInstance |
WebSocket | The WebSocket instance that was just connected. |
request |
Object | The request object included with the new connection. |
Listens to Events:
- event:ws_server -> connection
paramExists(requestObj, param, nullAllowedopt) → {Boolean}
Checks a JSON-RPC 2.0 request object for the existence of a specific parameter.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
requestObj |
Object | The JSON-RPC 2.0 request object to check for a parameter. | ||
param |
String | The parameter name to check for. | ||
nullAllowed |
Boolean |
<optional> |
true | If true, null values are considered as existing, otherwise they are considered as non-existent. |
Returns:
True if the specified parameter exists, false otherwise.
- Type
- Boolean
ping()
Pings all connnected WebSocket clients to ensure that they're still alive
and active. This function is usually invoked through a timer created by the
startWSServer function. Any WebSocket connnections that do not respond to
pings are automatically closed.
processRPCRequest(requestData, sessionObj)
Main RPC request handler for all endpoints. Successfully parsed requests are passed to invokeAPIFunction otherwise an
error is immediately returned.
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
requestData |
String | The raw, unparsed request body. | |||||||||||||||
sessionObj |
Object | An object containing data for the current sesssion.
The contents of this object will differ depending on the type of endpoint that received the original request.
Properties
|
registerAPIFunction(filename)
Registers an API function handler stored in a specified file in the internal
_APIFunctions
array.
Parameters:
Name | Type | Description |
---|---|---|
filename |
String | The full path of the file to register as an API handler. |
removePendingCashout(fromAccount, type, network) → {Object}
Removes a pending cashout transaction from the
namespace.cp.pendingCashouts
array.
Parameters:
Name | Type | Description |
---|---|---|
fromAccount |
String | The account address that is cashing out. |
type |
String | The cryptocurrency type associated with the transaction (e.g. "bitcoin"). |
network |
String | The cryptocurrency sub-network associated with the transaction (e.g. "main" or "test3"). |
- Source:
Returns:
The pending cashout transaction removed from the internal
namespace.cp.pendingCashouts
array, of null
if no matching transaction exists.
- Type
- Object
(async) saveAccount(accountObj) → {Promise}
Saves a new or existing (updated) account.
Parameters:
Name | Type | Description |
---|---|---|
accountObj |
AccountObject | Contains the account information to save. |
- Source:
Returns:
The resolved promise returns
true
if the account
was successfully saved, false
false otherwise.
- Type
- Promise
sendBroadcast(fromPID, sendData, excludeopt)
Sends a broadcast message to all connected WSS clients.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
fromPID |
String | The private ID of the sender. | ||
sendData |
* | The data to send to the recipients. | ||
exclude |
Object |
<optional> |
null | If not omitted or null, this object should
contain an indexed rcp array of recpients to exclude from
the broadcast. |
- Source:
sendDirect(fromPID, toArray, sendData)
Sends a direct message to a list of connected WSS clients.
Parameters:
Name | Type | Description |
---|---|---|
fromPID |
String | The private ID of the sender. |
toArray |
Array | Indexed list of recipient private IDs. |
sendData |
* | The data to send to the recipients. |
- Source:
sendError(code, message, sessionObj, dataopt)
Generates a final JSON-RPC 2.0 error object and sends it to the requestor via the source endpoint.
Parameters:
Name | Type | Attributes | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
code |
Number | A RPC error result code to include in the response. This code is non-standard and is defined on a per-application basis. | |||||||||||||||||||
message |
String | A human-readable error message to include in the response. | |||||||||||||||||||
sessionObj |
Object | An object containing data for the current sesssion.
The contents of this object will differ depending on the type of endpoint that received the original request.
Properties
|
|||||||||||||||||||
data |
* |
<optional> |
Any additional relevant data to include in the response. |
(async) sendIntercept(connectionObj, data)
A proxy or intercept function for a standard WebSocket
Typically this function is swapped into the WebSocket instance in connectTunnel where the extra parameter is introduced.
send
when the
socket is being tunneled.Typically this function is swapped into the WebSocket instance in connectTunnel where the extra parameter is introduced.
Parameters:
Name | Type | Description |
---|---|---|
connectionObj |
Object | The connection object containing a socket
reference, private_id , tunnel information object,
tunnelServerMessages , and other information for the tunneled connection. |
data |
* | The message to send to the tunneled socket. |
- Source:
sendResult(result, sessionObj)
Generates a final JSON-RPC 2.0 response (result) object and sends it to the requestor via the source endpoint.
Parameters:
Name | Type | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
result |
Object | The result object to include with the JSON-RPC response object, usually the result of the RPC call. | ||||||||||||||||||
sessionObj |
Object | An object containing data for the current sesssion.
The contents of this object will differ depending on the type of endpoint that received the original request.
Properties
|
(async) sendTunnelMessage(connectionObject, data)
Sends a message directly to a tunneled WebSocket. Used when the
message would otherwuise be intercepted after the tunnel has already
been established (for example, a tunnel "close" message.)
Parameters:
Name | Type | Description |
---|---|---|
connectionObject |
Object | The tunneled connection object containing a
socket reference, tunnel information object,
and other information for the tunneled connection to send to. |
data |
* | The data to send to the tunneled connection. |
- Source:
sendUpdate(toArray, sendData, fromPIDopt)
Sends a server update message to a list of connected WSS clients.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
toArray |
Array | Indexed list of recipient private IDs. | ||
sendData |
* | The data to send to the recipients. | ||
fromPID |
String |
<optional> |
null | The private ID of the sender. If omitted, the message is a non-peer-initiated update. |
- Source:
setDefaultHeaders(serverResponse)
Adds the default HTTP headers, as defined in rpc_options.http_headers,
to a HTTP / HTTPS response object.
Parameters:
Name | Type | Description |
---|---|---|
serverResponse |
Object | The ServerResponse object to add default headers to. |
(async) startDatabase(dbAdapteropt) → {Promise}
Starts a database adapter and makes it available to the application.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
dbAdapter |
String |
<optional> |
null | The database adapter to start. The name must match one of those defined in the config.CP.API.database.adapters objects. If null or not supplied, the adapter (if applicable), is determined from the configCP.API.database.url property. |
Returns:
The returned promise resolves with
true
if the database could be
successfully started. An Error
object is included with a rejection on any failure.
- Type
- Promise
(async) startHTTPServer()
Attempts to start the JSON-RPC 2.0 HTTP server using the default rpc_options. The onStartHTTPServer function is invoked when
the server is successfully started. The handleHTTPRequest function handles requests.
startWSServer()
Attempts to start the JSON-RPC 2.0 WebSocket server using the default rpc_options. The onStartWSServer function is invoked when
the server is successfully started.
(async) updateAccount(accountObj) → {Promise}
Updates the "updated" (date/time) property of an existing account. Any other changes to
account information should use saveAccount in order to maintain the account's history.
Parameters:
Name | Type | Description |
---|---|---|
accountObj |
AccountObject | Contains the account information to update. This object
must contain the primary_key value of the row to update. |
- Source:
Returns:
The resolved promise returns
true
if the account
was successfully updated, false
false otherwise.
- Type
- Promise
(async) updateAllTxFees(startAutoUpdateopt, sequentialopt)
Updates the internal transaction fees for all cryptocurrencies and sub-networks defined
in the global
config
object using the cryptocurrency handlers' updateTxFees
functions (i.e. some updates may be omitted if the update time limits have not elapsed).
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
startAutoUpdate |
Boolean |
<optional> |
true | If true, the automatic update interval defined in the
global config object for each cryptocurrency/network is (independently) started.
If false, transaction fees must be updated manually ir required. |
sequential |
Boolean |
<optional> |
true | If true, each new update is started when the previous one is completed, otherwise they're all executed simultaneously. |
- Source:
validateJSONRPC(dataObj) → {String}
Verifies whether a data object is a valid JSON-RPC 2.0 request.
Parameters:
Name | Type | Description |
---|---|---|
dataObj |
Object | The parsed object to check for validity. |
- Source:
- See:
Returns:
A description of the validation failure, or null if the validation passed.
- Type
- String
Type Definitions
AccountObject
An object containing individual account properties. A player may have multiple
accounts.
Type:
- Object
Properties:
Name | Type | Description |
---|---|---|
type |
String | The address type. Supported values include: "bitcoin |
chain |
Number | The HD wallet chain value used in the derivation path. |
addressIndex |
Number | The HD wallet address index used in the derivation path. |
address |
String | The generated cryptocurrency address for the account. |
network |
String | The sub-network, if applicable, to which the address belongs. For example "main", "test3", etc. |
pwhash |
String | The SHA256 hash of the password associated with the account. |
balance |
BigInteger | The current account balance in the lowest denomination of
the associated cryptocurrency (e.g. satoshis if type="bitcoin" ). |
updated |
String | The ISO8601 date/time that this account object was last updated. |
wallet |
Object | The HD wallet containig the private and public keys as well as the WIF. |
- Source:
- See:
AccountObject
An object containing player account information of an associated smart contract, usually
as part of a player's
account
property.
Type:
- Object
Properties:
Name | Type | Attributes | Description |
---|---|---|---|
address |
String | The cryptocurrency address associated with the account (and used as the primary identifier). | |
type |
String | The cryptocurrency type of the address . Valid values include: "bitcoin" |
|
network |
String | The sub-network of the address , if applicable. Valid values include:
"main", "test3" |
|
password |
String | The password associated with the account. | |
balance |
String |
<optional> |
Optional balance for the account (typically this value is ignored in favour
of the database balance for the account). |
- Source:
ContractObject
A CypherPoker.JS proxy smart contract object.
Type:
- Object
Properties:
Name | Type | Default | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
contractID |
String | The ID of the contract. | ||||||||||||||||
table |
TableObject | The table associated with the contract. | ||||||||||||||||
players |
Array | Indexed array of player object instances associated with the contract. | ||||||||||||||||
prime |
String | The root prime number value associated with the contract. | ||||||||||||||||
pot |
String | "0" | A numeric string representing the value currently held by the contract "pot" (the total subtracted from players' initial balances), to be awarded to the hand's winner(s). | |||||||||||||||
cardDecks |
Object | Contains the currently active card decks associated with the contract.
Properties
|
||||||||||||||||
history |
Object | Contains a history of card generation, encryption, and decryption operations for correctness analysis. |
- Source:
Exposed_API_Objects
Server objects exposed to API modules.
Type:
- Object
- Default Value:
- {
namespace:namespace,
config:config,
getConfigByPath:getConfigByPath,
require:require,
process:process,
Buffer:Buffer,
request:request,
console:console,
module:module,
hostEnv:hostEnv,
setInterval:setInterval,
clearInterval:clearInterval,
setTimeout:setTimeout,
clearTimeout:clearTimeout,
crypto:crypto,
bigInt:bigInt, getHandler:getHandler
bitcoin:bitcoin,
secp256k1:secp256k1,
sendResult:sendResult,
sendError:sendError,
buildJSONRPC:buildJSONRPC,
paramExists:paramExists,
JSONRPC_ERRORS:JSONRPC_ERRORS }
- {
namespace:namespace,
- Source:
Exposed_Library_Objects
Server objects exposed to external library, adapter, gateway, and other add-on
modules. Note that because libraries are not executed in their own virtual machines
they have access to most top-level objects.
Type:
- Object
- Default Value:
- {
namespace:namespace,
config:config,
require:require,
Buffer:Buffer,
request:request,
console:console,
module:module,
hostEnv:hostEnv,
setInterval:setInterval,
clearInterval:clearInterval,
setTimeout:setTimeout,
clearTimeout:clearTimeout,
bigInt:bigInt,
crypto:crypto,
getHandler:getHandler,
bitcoin:bitcoin,
secp256k1:secp256k1,
sendResult:sendResult,
sendError:sendError,
buildJSONRPC:buildJSONRPC,
paramExists:paramExists,
getConfigByPath:getConfigByPath,
mkdirSync:mkdirSync,
validateJSONRPC:validateJSONRPC,
handleHTTPRequest:handleHTTPRequest ,
processRPCRequest:processRPCRequest,
invokeAPIFunction:invokeAPIFunction,
JSONRPC_ERRORS:JSONRPC_ERRORS
}
- {
namespace:namespace,
- Source:
HTTP_Headers_Array
HTTP response headers used with HTTP / HTTPS endpoints.
Type:
- Array
- Default Value:
- [{"Access-Control-Allow-Origin" : "*"}, {"Content-Type" : "application/json-rpc"}]
- Source:
httpserv
A HTTP endpoint ("http" module).
Type:
- http
TableObject
A CypherPoker.JS table object associated with a game.
Type:
- Object
Properties:
Name | Type | Description |
---|---|---|
ownerPID |
String | The private ID of the owner / creator of the table. |
tableID |
String | The pseudo-randomly generated, unique table ID of the table. |
tableName |
String | The name given to the table by the owner. |
requiredPID |
Array | Indexed array of private IDs of peers required to join this room before it's considered full or ready. |
joinedPID |
Array | Indexed array of private IDs that have been accepted by the owner. When a contract is first created, this array should only have one element: the owner's PID. |
restorePID |
Array | Copy of the original private IDs in the requiredPID array
used to restore it if members of the joinePID array leave the table. |
tableInfo |
Object | Additional information to be included with the table. |
- Source:
wsserv
A WebSocket endpoint ("ws" module).
Type:
- ws