Skip to content

Commit

Permalink
WIP new typescript library for better communication
Browse files Browse the repository at this point in the history
  • Loading branch information
marpme committed Apr 19, 2018
1 parent e6b1002 commit 0a05d2d
Show file tree
Hide file tree
Showing 42 changed files with 1,757 additions and 317 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
lib
4 changes: 4 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
tsconfig.json
src
lib
node_modules
6 changes: 6 additions & 0 deletions dist/API.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export declare abstract class API {
commands: Array<string>;
isCommand(command: string): boolean;
getCommands(): Array<string>;
abstract getBalance(account?: string): Promise<number>;
}
102 changes: 102 additions & 0 deletions dist/API.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var API = /** @class */ (function () {
function API() {
this.commands = new Array('addMultiSigAddress', 'backupWallet', 'createRawTransaction', 'decodeRawTransaction', 'dumpPrivKey', 'encryptWallet', 'getAccount', 'getAccountAddress', 'getAddressesByAccount', 'getBalance', 'getBlock', 'getBlockCount', 'getBlockHash', 'getConnectionCount', 'getDifficulty', 'getGenerate', 'getHashesPerSec', 'getInfo', 'getMemoryPool', 'getMiningInfo', 'getNewAddress', 'getRawTransaction', 'getReceivedByAccount', 'getReceivedByAddress', 'getTransaction', 'getWork', 'help', 'importPrivKey', 'importAddress', 'keyPoolRefill', 'listAccounts', 'listReceivedByAccount', 'listReceivedByAddress', 'listSinceBlock', 'listTransactions', 'listUnspent', 'move', 'sendFrom', 'sendMany', 'sendRawTransaction', 'sendToAddress', 'setAccount', 'setGenerate', 'setTxFee', 'signMessage', 'signRawTransaction', 'stop', 'validateAddress', 'verifyMessage', 'walletLock', 'walletPassphrase', 'walletPassphraseChange');
/*abstract getBlock(hash: string, txinfo?: string): Promise<Block>
abstract getBlockCount(): Client
abstract getBlockHash(): Client
abstract getConnectionCount(): Client
abstract getDifficulty(): Client
abstract getGenerate(): Client
abstract getHashesPerSec(): Client
abstract getInfo(): Client
abstract getMemoryPool(): Client
abstract getMiningInfo(): Client
abstract getNewAddress(): Client
abstract getRawTransaction(): Client
abstract getReceivedByAccount(): Client
abstract getReceivedByAddress(): Client
abstract getTransaction(): Client
abstract getWork(): Client
abstract help(): Client
abstract importPrivKey(): Client
abstract importAddress(): Client
abstract keyPoolRefill(): Client
abstract listAccounts(): Client
abstract listReceivedByAccount(): Client
abstract listReceivedByAddress(): Client
abstract listSinceBlock(): Client
abstract listTransactions(): Client
abstract listUnspent(): Client
abstract move(): Client
abstract sendFrom(): Client
abstract sendMany(): Client
abstract sendRawTransaction(): Client
abstract sendToAddress(): Client
abstract setAccount(): Client
abstract setGenerate(): Client
abstract setTxFee(): Client
abstract signMessage(): Client
abstract signRawTransaction(): Client
abstract stop(): Client
abstract validateAddress(): Client
abstract verifyMessage(): Client
abstract walletLock(): Client
abstract walletPassphrase(): Client
abstract walletPassphraseChange(): Client*/
}
API.prototype.isCommand = function (command) {
var lowerCommand = command.toLowerCase();
var lowerCaseCommands = this.getCommands().map(function (item) {
return item.toLowerCase();
});
return lowerCaseCommands.indexOf(lowerCommand) !== -1;
};
API.prototype.getCommands = function () {
return this.commands;
};
return API;
}());
exports.API = API;
25 changes: 25 additions & 0 deletions dist/Block.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export interface Block {
hash: string;
confirmations: string;
size: string;
height: string;
version: string;
algo_id: string;
algo: string;
mined_hash: string;
merkleroot: string;
mint: string;
time: string;
nonce: string;
bits: string;
difficulty: string;
previousblockhash?: string;
nextblockhash?: string;
flags: string;
proofhash: string;
entropybit: string;
modifier: string;
modifierchecksum: string;
tx: string;
signature: string;
}
2 changes: 2 additions & 0 deletions dist/Block.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
14 changes: 14 additions & 0 deletions dist/Client.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { API } from './API';
import { RPCErrorCode } from './RPCErrorCode';
import { ClientOption } from './ClientOption';
export declare class Client extends API {
options: ClientOption;
errors: RPCErrorCode[];
constructor(options: ClientOption);
private invalid(command);
private send(command, ...args);
private exec(command);
private auth(user, pass);
private unlock(command, args, fn);
getBalance(account?: string): Promise<number>;
}
145 changes: 145 additions & 0 deletions dist/Client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var API_1 = require("./API");
var http = require("http");
var RPCErrorCode_1 = require("./RPCErrorCode");
var https = require("https");
var Client = /** @class */ (function (_super) {
__extends(Client, _super);
function Client(options) {
var _this = _super.call(this) || this;
_this.options = __assign({ host: 'localhost', port: 20102, method: 'POST', user: '', pass: '', headers: {
Host: 'localhost',
Authorization: '',
}, passphrasecallback: null, https: false, ca: null }, options);
if (_this.options.user && _this.options.pass) {
_this.options.headers.Authorization = "Basic " + new Buffer(_this.options.user + ':' + _this.options.pass).toString('base64');
}
return _this;
}
Client.prototype.invalid = function (command) {
var args = Array.prototype.slice.call(arguments, 1), fn = args.pop();
if (typeof fn !== 'function') {
fn = console.log;
}
return fn(new Error('No such command "' + command + '"'));
};
Client.prototype.send = function (command) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var rpcData = {
id: new Date().getTime(),
method: command.toLowerCase(),
params: args.filter(function (item) { return !!item; }),
};
var options = this.options;
options.headers['Content-Length'] = JSON.stringify(rpcData).length;
var request;
if (this.options.https === true) {
request = https.request;
}
else {
request = http.request;
}
var promisedRequest = new Promise(function (resolve, reject) {
var rpcRequest = request(options, function (res) {
var _this = this;
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
try {
var rpcResponse = JSON.parse(data);
if (rpcResponse.id != rpcData.id) {
throw new Error('Possible Man-in-the-middle Attack!!!');
}
if (rpcResponse.error) {
if (rpcResponse.error.code ===
RPCErrorCode_1.RPCErrorCode.RPC_WALLET_UNLOCK_NEEDED &&
options.passphrasecallback) {
//TODO: Handle special case :thinking:
return _this.unlock(command, args, function () { });
}
else {
var err = JSON.stringify(rpcResponse);
return reject(err);
}
}
console.log(rpcResponse);
resolve(rpcResponse.result !== null ? rpcResponse.result : rpcResponse);
}
catch (exception) {
var errMsg = res.statusCode !== 200
? 'Invalid params ' + res.statusCode
: 'Failed to parse JSON';
errMsg += ' : ' + JSON.stringify(data);
return reject(new Error(errMsg));
}
});
});
rpcRequest.on('error', function (error) { return reject(error); });
rpcRequest.end(JSON.stringify(rpcData));
});
return promisedRequest;
};
Client.prototype.exec = function (command) {
var func = this.isCommand(command) ? 'send' : 'invalid';
return this[func].apply(this, arguments);
};
Client.prototype.auth = function (user, pass) {
if (user && pass) {
var authString = 'Basic ' + new Buffer(user + ':' + pass).toString('base64');
this.options.headers['Authorization'] = authString;
}
return this;
};
Client.prototype.unlock = function (command, args, fn) {
var self = this;
var retry = function (err) {
if (err) {
fn(err);
}
else {
var sendargs = args.slice();
sendargs.unshift(command);
sendargs.push(fn);
self.send.apply(self, sendargs);
}
};
this.options.passphrasecallback(command, args, function (err, passphrase, timeout) {
if (err) {
fn(err);
}
else {
self.send('walletpassphrase', passphrase, timeout, retry);
}
});
};
Client.prototype.getBalance = function (account) {
return this.send('getbalance', account).catch(console.error);
};
return Client;
}(API_1.API));
exports.Client = Client;
15 changes: 15 additions & 0 deletions dist/ClientOption.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export interface ClientOption {
host?: string;
port?: number;
method?: string;
user?: string;
pass?: string;
headers?: HeaderOption;
passphrasecallback?: Function;
https?: boolean;
ca?: string;
}
export interface HeaderOption {
Host?: string;
Authorization?: string;
}
2 changes: 2 additions & 0 deletions dist/ClientOption.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
60 changes: 60 additions & 0 deletions dist/Command.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Client } from './Client';
import { Transaction } from './Transaction';
import { Block } from './Block';
export declare abstract class API {
commands: Array<string>;
isCommand(command: string): boolean;
getCommands(): Array<string>;
abstract addMultiSigAddress(nrequire: string, keys: string[], account: string): Promise<string>;
abstract backupWallet(destination: string): Promise<null>;
abstract createRawTransaction(transactions: Transaction[], sendAddressAndAmount: any): Promise<string>;
abstract decodeRawTransaction(hexString: string): Promise<Transaction>;
abstract dumpPrivKey(address: string): Promise<string>;
abstract encryptWallet(passphrase: string): Promise<string>;
abstract getAccount(address: string): Promise<string>;
abstract getAccountAddress(account: string): Promise<string>;
abstract getAddressesByAccount(account: string): Promise<string>;
abstract getBalance(account?: string): Promise<number>;
abstract getBlock(hash: string, txinfo?: string): Promise<Block>;
abstract getBlockCount(): Client;
abstract getBlockHash(): Client;
abstract getConnectionCount(): Client;
abstract getDifficulty(): Client;
abstract getGenerate(): Client;
abstract getHashesPerSec(): Client;
abstract getInfo(): Client;
abstract getMemoryPool(): Client;
abstract getMiningInfo(): Client;
abstract getNewAddress(): Client;
abstract getRawTransaction(): Client;
abstract getReceivedByAccount(): Client;
abstract getReceivedByAddress(): Client;
abstract getTransaction(): Client;
abstract getWork(): Client;
abstract help(): Client;
abstract importPrivKey(): Client;
abstract importAddress(): Client;
abstract keyPoolRefill(): Client;
abstract listAccounts(): Client;
abstract listReceivedByAccount(): Client;
abstract listReceivedByAddress(): Client;
abstract listSinceBlock(): Client;
abstract listTransactions(): Client;
abstract listUnspent(): Client;
abstract move(): Client;
abstract sendFrom(): Client;
abstract sendMany(): Client;
abstract sendRawTransaction(): Client;
abstract sendToAddress(): Client;
abstract setAccount(): Client;
abstract setGenerate(): Client;
abstract setTxFee(): Client;
abstract signMessage(): Client;
abstract signRawTransaction(): Client;
abstract stop(): Client;
abstract validateAddress(): Client;
abstract verifyMessage(): Client;
abstract walletLock(): Client;
abstract walletPassphrase(): Client;
abstract walletPassphraseChange(): Client;
}
Loading

0 comments on commit 0a05d2d

Please sign in to comment.