Skip to content

Instantly share code, notes, and snippets.

@evias

evias/nem-sdk-v1.6.2.js

Last active Dec 27, 2018
Embed
What would you like to do?
nem-sdk-v1.6.2.js
This file has been truncated, but you can view the full file.
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets the AccountMetaDataPair of an account.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {object} - An [AccountMetaDataPair]{@link http://bob.nem.ninja/docs/#accountMetaDataPair} object
*/
var data = function data(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/get',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the AccountMetaDataPair of an account with a public Key.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} publicKey - An account public key
*
* @return {object} - An [AccountMetaDataPair]{@link http://bob.nem.ninja/docs/#accountMetaDataPair} object
*/
var dataFromPublicKey = function dataFromPublicKey(endpoint, publicKey) {
// Configure the public key request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/get/from-public-key',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'publicKey': publicKey }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets an array of harvest info objects for an account.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [HarvestInfo]{@link http://bob.nem.ninja/docs/#harvestInfo} objects
*/
var harvestedBlocks = function harvestedBlocks(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/harvests',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets an array of TransactionMetaDataPair objects where the recipient has the address given as parameter to the request.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} txHash - The 256 bit sha3 hash of the transaction up to which transactions are returned. (optional)
* @param {string} txId - The transaction id up to which transactions are returned. (optional)
*
* @return {array} - An array of [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} objects
*/
var incomingTransactions = function incomingTransactions(endpoint, address, txHash, txId) {
// Arrange
var params = { 'address': address };
if (txHash) params['hash'] = txHash;
if (txId) params['id'] = txId;
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/transfers/incoming',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: params
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets an array of TransactionMetaDataPair objects where the sender has the address given as parameter to the request.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} txHash - The 256 bit sha3 hash of the transaction up to which transactions are returned. (optional)
* @param {string} txId - The transaction id up to which transactions are returned. (optional)
*
* @return {array} - An array of [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} objects
*/
var outgoingTransactions = function outgoingTransactions(endpoint, address, txHash, txId) {
// Arrange
var params = { 'address': address };
if (txHash) params['hash'] = txHash;
if (txId) params['id'] = txId;
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/transfers/outgoing',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: params
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the array of transactions for which an account is the sender or receiver and which have not yet been included in a block.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [UnconfirmedTransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#unconfirmedTransactionMetaDataPair} objects
*/
var unconfirmedTransactions = function unconfirmedTransactions(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/unconfirmedTransactions',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets information about the maximum number of allowed harvesters and how many harvesters are already using the node
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - An [UnlockInfo]{@link http://bob.nem.ninja/docs/#retrieving-the-unlock-info} object
*/
var unlockInfo = function unlockInfo(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/unlocked/info',
method: 'POST',
headers: _headers2.default.urlEncoded
// Send the request
};return (0, _send2.default)(options);
};
/**
* Unlocks an account (starts harvesting).
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} privateKey - A delegated account private key
*
* @return - Nothing
*/
var startHarvesting = function startHarvesting(endpoint, privateKey) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/unlock',
method: 'POST',
json: true,
body: { 'value': privateKey }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Locks an account (stops harvesting).
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} privateKey - A delegated account private key
*
* @return - Nothing
*/
var stopHarvesting = function stopHarvesting(endpoint, privateKey) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/lock',
method: 'POST',
json: true,
body: { 'value': privateKey }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the AccountMetaDataPair of the account for which the given account is the delegate account
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {object} - An [AccountMetaDataPair]{@link http://bob.nem.ninja/docs/#accountMetaDataPair} object
*/
var forwarded = function forwarded(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/get/forwarded',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets namespaces that an account owns
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} parent - The namespace parent (optional)
*
* @return {object} - An array of [NamespaceMetaDataPair]{@link http://bob.nem.ninja/docs/#namespaceMetaDataPair} objects
*/
var namespacesOwned = function namespacesOwned(endpoint, address, parent) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/namespace/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address, 'parent': parent || "" }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaic definitions that an account has created
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} parent - The namespace parent (optional)
*
* @return {object} - An array of [MosaicDefinition]{@link http://bob.nem.ninja/docs/#mosaicDefinition} objects
*/
var mosaicDefinitionsCreated = function mosaicDefinitionsCreated(endpoint, address, parent) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/mosaic/definition/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address, 'parent': parent || "" }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaic definitions that an account owns
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [MosaicDefinition]{@link http://bob.nem.ninja/docs/#mosaicDefinition} objects
*/
var mosaicDefinitions = function mosaicDefinitions(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/mosaic/owned/definition',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaics that an account owns
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [Mosaic]{@link http://bob.nem.ninja/docs/#mosaic} objects
*/
var mosaicsOwned = function mosaicsOwned(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/mosaic/owned',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets all transactions of an account
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} txHash - The 256 bit sha3 hash of the transaction up to which transactions are returned. (optional)
* @param {string} txId - The transaction id up to which transactions are returned. (optional)
*
* @return {array} - An array of [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} objects
*/
var allTransactions = function allTransactions(endpoint, address, txHash, txId) {
// Arrange
var params = { 'address': address };
if (txHash) params['hash'] = txHash;
if (txId) params['id'] = txId;
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/transfers/all',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: params
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
data: data,
dataFromPublicKey: dataFromPublicKey,
unlockInfo: unlockInfo,
forwarded: forwarded,
mosaics: {
owned: mosaicsOwned,
definitions: mosaicDefinitionsCreated,
allDefinitions: mosaicDefinitions
},
namespaces: {
owned: namespacesOwned
},
harvesting: {
blocks: harvestedBlocks,
start: startHarvesting,
stop: stopHarvesting
},
transactions: {
incoming: incomingTransactions,
outgoing: outgoingTransactions,
unconfirmed: unconfirmedTransactions,
all: allTransactions
}
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],2:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _nodes = require('../../model/nodes');
var _nodes2 = _interopRequireDefault(_nodes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Audit an apostille file
*
* @param {string} publicKey - The signer public key
* @param {string} data - The file data of audited file
* @param {string} signedData - The signed data into the apostille transaction message
*
* @return {boolean} - True if valid, false otherwise
*/
var audit = function audit(publicKey, data, signedData) {
// Configure the request
var options = {
url: _nodes2.default.apostilleAuditServer,
method: 'POST',
headers: _headers2.default.urlEncoded,
qs: { 'publicKey': publicKey, 'data': data, 'signedData': signedData }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
audit: audit
};
},{"../../model/nodes":27,"./headers":5,"./send":10}],3:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets the current height of the block chain.
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - A [BlockHeight]{@link http://bob.nem.ninja/docs/#block-chain-height} object
*/
var height = function height(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/chain/height',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the current last block of the chain.
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} -
*/
var lastBlock = function lastBlock(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/chain/last-block',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets network time (in ms)
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - A [communicationTimeStamps]{@link http://bob.nem.ninja/docs/#communicationTimeStamps} object
*/
var time = function time(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/time-sync/network-time',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
height: height,
lastBlock: lastBlock,
time: time
};
},{"../../utils/helpers":51,"./send":10}],4:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Determines if NIS is up and responsive.
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - A [NemRequestResult]{@link http://bob.nem.ninja/docs/#nemRequestResult} object
*/
var heartbeat = function heartbeat(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/heartbeat',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
heartbeat: heartbeat
};
},{"../../utils/helpers":51,"./send":10}],5:[function(require,module,exports){
(function (Buffer){
'use strict';
/**
* An url encoded header
*
* @type {object}
*/
var urlEncoded = {
'Content-Type': 'application/x-www-form-urlencoded'
/**
* Create an application/json header
*
* @param {data} - A json string
*
* @return {object} - An application/json header with content length
*/
};var json = function json(data) {
return {
"Content-Type": "application/json",
"Content-Length": Buffer.from(data).byteLength
};
};
module.exports = {
urlEncoded: urlEncoded,
json: json
};
}).call(this,require("buffer").Buffer)
},{"buffer":157}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _account = require('./account');
var _account2 = _interopRequireDefault(_account);
var _apostille = require('./apostille');
var _apostille2 = _interopRequireDefault(_apostille);
var _chain = require('./chain');
var _chain2 = _interopRequireDefault(_chain);
var _endpoint = require('./endpoint');
var _endpoint2 = _interopRequireDefault(_endpoint);
var _market = require('./market');
var _market2 = _interopRequireDefault(_market);
var _mosaic = require('./mosaic');
var _mosaic2 = _interopRequireDefault(_mosaic);
var _namespace = require('./namespace');
var _namespace2 = _interopRequireDefault(_namespace);
var _supernodes = require('./supernodes');
var _supernodes2 = _interopRequireDefault(_supernodes);
var _transaction = require('./transaction');
var _transaction2 = _interopRequireDefault(_transaction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
account: _account2.default,
apostille: _apostille2.default,
chain: _chain2.default,
endpoint: _endpoint2.default,
market: _market2.default,
mosaic: _mosaic2.default,
namespace: _namespace2.default,
supernodes: _supernodes2.default,
transaction: _transaction2.default
};
},{"./account":1,"./apostille":2,"./chain":3,"./endpoint":4,"./market":7,"./mosaic":8,"./namespace":9,"./supernodes":11,"./transaction":12}],7:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _nodes = require('../../model/nodes');
var _nodes2 = _interopRequireDefault(_nodes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets market information from Poloniex api
*
* @return {object} - A MarketInfo object
*/
var xem = function xem() {
// Configure the request
var options = {
url: _nodes2.default.marketInfo,
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'command': 'returnTicker' }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets BTC price from blockchain.info API
*
* @return {object} - A MarketInfo object
*/
var btc = function btc() {
// Configure the request
var options = {
url: _nodes2.default.btcPrice,
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'cors': true }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
xem: xem,
btc: btc
};
},{"../../model/nodes":27,"./headers":5,"./send":10}],8:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets the current supply of a mosaic
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} id - A mosaic id
*
* @return {object} - A mosaicSupplyInfo object
*/
var supply = function supply(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/mosaic/supply',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'mosaicId': id }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
supply: supply
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],9:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets root namespaces.
*
* @param {object} endpoint - An NIS endpoint object
* @param {number} id - The namespace id up to which root namespaces are returned (optional)
*
* @return {object} - An array of [NamespaceMetaDataPair]{@link http://bob.nem.ninja/docs/#namespaceMetaDataPair} objects
*/
var roots = function roots(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/namespace/root/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: undefined === id ? { 'pageSize': 100 } : { 'id': id, 'pageSize': 100 }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaic definitions of a namespace
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} id - A namespace id
*
* @return {object} - An array of [MosaicDefinition]{@link http://bob.nem.ninja/docs/#mosaicDefinition} objects
*/
var mosaicDefinitions = function mosaicDefinitions(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/namespace/mosaic/definition/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'namespace': id }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the namespace with given id.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} id - A namespace id
*
* @return {object} - A [NamespaceInfo]{@link http://bob.nem.ninja/docs/#namespace} object
*/
var info = function info(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/namespace',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'namespace': id }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
roots: roots,
mosaicDefinitions: mosaicDefinitions,
info: info
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _request = require('request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Send a request
*
* @param {object} options - The options of the request
*
* @return {Promise} - A resolved promise with the requested data or a rejection with error data
*/
var send = function send(options) {
return new Promise(function (resolve, reject) {
(0, _request2.default)(options, function (error, response, body) {
var data = void 0;
if (_helpers2.default.isJSON(body)) {
data = JSON.parse(body);
} else {
data = body;
}
if (!error && response.statusCode == 200) {
resolve(data);
} else {
if (!error) {
reject({ "code": 0, "data": data });
} else {
reject({ "code": -1, "data": error });
}
}
});
});
};
exports.default = send;
},{"../../utils/helpers":51,"request":367}],11:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _nodes = require('../../model/nodes');
var _nodes2 = _interopRequireDefault(_nodes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets all nodes of the node reward program
*
* @return {array} - An array of SuperNodeInfo objects
*/
var all = function all() {
// Configure the request
var options = {
url: _nodes2.default.supernodes,
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the nearest supernodes
*
* @param {object} coords - A coordinates object: https://www.w3schools.com/html/html5_geolocation.asp
*
* @return {array} - An array of supernodeInfo objects
*/
var nearest = function nearest(coords) {
var obj = {
"latitude": coords.latitude,
"longitude": coords.longitude,
"numNodes": 5
// Configure the request
};var options = {
url: 'http://199.217.113.179:7782/nodes/nearest',
method: 'POST',
json: true,
body: obj
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the all supernodes by status
*
* @param {number} status - 0 for all nodes, 1 for active nodes, 2 for inactive nodes
*
* @return {array} - An array of supernodeInfo objects
*/
var get = function get(status) {
var obj = {
"status": undefined === status ? 1 : status
// Configure the request
};var options = {
url: 'http://199.217.113.179:7782/nodes',
method: 'POST',
json: true,
body: obj
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
all: all,
nearest: nearest,
get: get
};
},{"../../model/nodes":27,"./send":10}],12:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Broadcast a transaction to the NEM network
*
* @param {object} endpoint - An NIS endpoint object
* @param {object} obj - A RequestAnnounce object
*
* @return {object} - A [NemAnnounceResult]{@link http://bob.nem.ninja/docs/#nemAnnounceResult} object
*/
var announce = function announce(endpoint, serializedTransaction) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/transaction/announce',
method: 'POST',
headers: _headers2.default.json(serializedTransaction),
json: JSON.parse(serializedTransaction)
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets a TransactionMetaDataPair object from the chain using it's hash
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} txHash - A transaction hash
*
* @return {object} - A [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} object
*/
var byHash = function byHash(endpoint, txHash) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/transaction/get',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'hash': txHash }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
announce: announce,
byHash: byHash
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],13:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if socket is open
*
* @param {object} connector - A connector object
*
* @return {boolean} - True if open, false otherwise
*/
var checkReadyState = function checkReadyState(connector) {
var self = connector;
if (_sockjs.SockJS ? self.socket.readyState !== _sockjs.SockJS.OPEN : self.socket.readyState !== _sockjsClient2.default.OPEN) {
return false;
}
return true;
};
/**
* Request the account data of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestAccountData = function requestAccountData(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestData(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/get", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the recent transactions of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestRecentTransactions = function requestRecentTransactions(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/transfers/all", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the owned mosaic definitions of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestMosaicDefinitions = function requestMosaicDefinitions(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/mosaic/owned/definition", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the owned mosaics of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestMosaics = function requestMosaics(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/mosaic/owned", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the owned namespaces of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestNamespaces = function requestNamespaces(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/namespace/owned", {}, "{'account':'" + _address + "'}");
}
};
/**
* Subscribe to the account data channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeAccountData = function subscribeAccountData(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the recent transactions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeRecentTransactions = function subscribeRecentTransactions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/recenttransactions/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the unconfirmed transactions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeUnconfirmedTransactions = function subscribeUnconfirmedTransactions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/unconfirmed/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the confirmed transactions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeConfirmedTransactions = function subscribeConfirmedTransactions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/transactions/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the mosaic definitions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeMosaicDefinitions = function subscribeMosaicDefinitions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/mosaic/owned/definition/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the owned mosaics channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeMosaics = function subscribeMosaics(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/mosaic/owned/' + _address, function (data) {
callback(JSON.parse(data.body), _address);
});
};
/**
* Subscribe to the owned namespaces channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeNamespaces = function subscribeNamespaces(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/namespace/owned/' + _address, function (data) {
callback(JSON.parse(data.body), _address);
});
};
module.exports = {
requests: {
data: requestAccountData,
transactions: {
recent: requestRecentTransactions
},
mosaics: {
owned: requestMosaics,
definitions: requestMosaicDefinitions
},
namespaces: {
owned: requestNamespaces
}
},
subscribe: {
data: subscribeAccountData,
transactions: {
recent: subscribeRecentTransactions,
confirmed: subscribeConfirmedTransactions,
unconfirmed: subscribeUnconfirmedTransactions
},
mosaics: {
owned: subscribeMosaics,
definitions: subscribeMosaicDefinitions
},
namespaces: {
owned: subscribeNamespaces
}
}
};
},{"../../external/sockjs-0.3.4":21,"sockjs-client":390}],14:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if socket is open
*
* @param {object} connector - A connector object
*
* @return {boolean} - True if open, false otherwise
*/
var checkReadyState = function checkReadyState(connector) {
var self = connector;
if (_sockjs.SockJS ? self.socket.readyState !== _sockjs.SockJS.OPEN : self.socket.readyState !== _sockjsClient2.default.OPEN) {
return false;
}
return true;
};
/**
* Subscribe to the new blocks channel
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
*
* @return the received data in the callback
*/
var subscribeNewBlocks = function subscribeNewBlocks(connector, callback) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
self.stompClient.subscribe('/blocks', function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the new height channel
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
*
* @return the received data in the callback
*/
var subscribeNewHeight = function subscribeNewHeight(connector, callback) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
self.stompClient.subscribe('/blocks/new', function (data) {
callback(JSON.parse(data.body));
});
};
module.exports = {
requests: {},
subscribe: {
height: subscribeNewHeight,
blocks: subscribeNewBlocks
}
};
},{"../../external/sockjs-0.3.4":21,"sockjs-client":390}],15:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
var _stomp = require('../../external/stomp');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a connector object
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {object} - A connector object
*/
var create = function create(endpoint, address) {
return {
endpoint: endpoint,
address: address.replace(/-/g, "").toUpperCase(),
socket: undefined,
stompClient: undefined,
connect: connect,
close: close
};
};
/**
* Tries to establish a connection.
*
* @return {promise} - A resolved or rejected promise
*/
var connect = function connect() {
var _this = this;
return new Promise(function (resolve, reject) {
var self = _this;
if (!_sockjs.SockJS) self.socket = new _sockjsClient2.default(self.endpoint.host + ':' + self.endpoint.port + '/w/messages');else self.socket = new _sockjs.SockJS(self.endpoint.host + ':' + self.endpoint.port + '/w/messages');
self.stompClient = _stomp.Stomp.over(self.socket);
self.stompClient.debug = false;
self.stompClient.connect({}, function (frame) {
resolve(true);
}, function (err) {
reject("Connection failed!");
});
});
};
/**
* Close a connection
*/
var close = function close() {
var self = this;
console.log("Connection to " + self.endpoint.host + " must be closed now.");
self.socket.close();
self.socket.onclose = function (e) {
console.log(e);
};
};
module.exports = {
create: create
};
},{"../../external/sockjs-0.3.4":21,"../../external/stomp":22,"sockjs-client":390}],16:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if socket is open
*
* @param {object} connector - A connector object
*
* @return {boolean} - True if open, false otherwise
*/
var checkReadyState = function checkReadyState(connector) {
var self = connector;
if (_sockjs.SockJS ? self.socket.readyState !== _sockjs.SockJS.OPEN : self.socket.readyState !== _sockjsClient2.default.OPEN) {
return false;
}
return true;
};
/**
* Subscribe to errors channel
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
*
* @return the received data in the callback
*/
var subscribe = function subscribe(connector, callback) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
self.stompClient.subscribe('/errors', function (data) {
callback(JSON.parse(data.body));
});
};
module.exports = {
subscribe: subscribe
};
},{"../../external/sockjs-0.3.4":21,"sockjs-client":390}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connector = require('./connector');
var _connector2 = _interopRequireDefault(_connector);
var _account = require('./account');
var _account2 = _interopRequireDefault(_account);
var _chain = require('./chain');
var _chain2 = _interopRequireDefault(_chain);
var _errors = require('./errors');
var _errors2 = _interopRequireDefault(_errors);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
connector: _connector2.default,
requests: {
account: _account2.default.requests,
chain: _chain2.default.requests
},
subscribe: {
account: _account2.default.subscribe,
chain: _chain2.default.subscribe,
errors: _errors2.default.subscribe
}
};
},{"./account":13,"./chain":14,"./connector":15,"./errors":16}],18:[function(require,module,exports){
'use strict';
var _keyPair = require('./keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _address = require('../model/address');
var _address2 = _interopRequireDefault(_address);
var _naclFast = require('../external/nacl-fast');
var _naclFast2 = _interopRequireDefault(_naclFast);
var _network = require('../model/network');
var _network2 = _interopRequireDefault(_network);
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Encrypt a private key for mobile apps (AES_PBKF2)
*
* @param {string} password - A wallet password
* @param {string} privateKey - An account private key
*
* @return {object} - The encrypted data
*/
var toMobileKey = function toMobileKey(password, privateKey) {
// Errors
if (!password || !privateKey) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
var salt = _cryptoJs2.default.lib.WordArray.random(256 / 8);
var key = _cryptoJs2.default.PBKDF2(password, salt, {
keySize: 256 / 32,
iterations: 2000
});
var iv = _naclFast2.default.randomBytes(16);
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = _cryptoJs2.default.AES.encrypt(_cryptoJs2.default.enc.Hex.parse(privateKey), key, encIv);
// Result
return {
encrypted: _convert2.default.ua2hex(iv) + encrypted.ciphertext,
salt: salt.toString()
};
};
/**
* Derive a private key from a password using count iterations of SHA3-256
*
* @param {string} password - A wallet password
* @param {number} count - A number of iterations above 0
*
* @return {object} - The derived private key
*/
var derivePassSha = function derivePassSha(password, count) {
// Errors
if (!password) throw new Error('Missing argument !');
if (!count || count <= 0) throw new Error('Please provide a count number above 0');
// Processing
var data = password;
console.time('sha3^n generation time');
for (var i = 0; i < count; ++i) {
data = _cryptoJs2.default.SHA3(data, {
outputLength: 256
});
}
console.timeEnd('sha3^n generation time');
// Result
return {
'priv': _cryptoJs2.default.enc.Hex.stringify(data)
};
};
/**
* Reveal the private key of an account or derive it from the wallet password
*
* @param {object} common- An object containing password and privateKey field
* @param {object} walletAccount - A wallet account object
* @param {string} algo - A wallet algorithm
*
* @return {object|boolean} - The account private key in and object or false
*/
var passwordToPrivatekey = function passwordToPrivatekey(common, walletAccount, algo) {
// Errors
if (!common || !walletAccount || !algo) throw new Error('Missing argument !');
var r = undefined;
if (algo === "trezor") {
// HW wallet
r = { 'priv': '' };
common.isHW = true;
} else if (!common.password) {
throw new Error('Missing argument !');
}
// Processing
if (algo === "pass:6k") {
// Brain wallets
if (!walletAccount.encrypted && !walletAccount.iv) {
// Account private key is generated simply using a passphrase so it has no encrypted and iv
r = derivePassSha(common.password, 6000);
} else if (!walletAccount.encrypted || !walletAccount.iv) {
// Else if one is missing there is a problem
//console.log("Account might be compromised, missing encrypted or iv");
return false;
} else {
// Else child accounts have encrypted and iv so we decrypt
var pass = derivePassSha(common.password, 20);
var obj = {
ciphertext: _cryptoJs2.default.enc.Hex.parse(walletAccount.encrypted),
iv: _convert2.default.hex2ua(walletAccount.iv),
key: _convert2.default.hex2ua(pass.priv)
};
var d = decrypt(obj);
r = { 'priv': d };
}
} else if (algo === "pass:bip32") {
// Wallets from PRNG
var _pass = derivePassSha(common.password, 20);
var _obj = {
ciphertext: _cryptoJs2.default.enc.Hex.parse(walletAccount.encrypted),
iv: _convert2.default.hex2ua(walletAccount.iv),
key: _convert2.default.hex2ua(_pass.priv)
};
var _d = decrypt(_obj);
r = { 'priv': _d };
} else if (algo === "pass:enc") {
// Private Key wallets
var _pass2 = derivePassSha(common.password, 20);
var _obj2 = {
ciphertext: _cryptoJs2.default.enc.Hex.parse(walletAccount.encrypted),
iv: _convert2.default.hex2ua(walletAccount.iv),
key: _convert2.default.hex2ua(_pass2.priv)
};
var _d2 = decrypt(_obj2);
r = { 'priv': _d2 };
} else if (!r) {
//console.log("Unknown wallet encryption method");
return false;
}
// Result
common.privateKey = r.priv;
return true;
};
/**
* Check if a private key correspond to an account address
*
* @param {string} priv - An account private key
* @param {number} network - A network id
* @param {string} _expectedAddress - The expected NEM address
*
* @return {boolean} - True if valid, false otherwise
*/
var checkAddress = function checkAddress(priv, network, _expectedAddress) {
// Errors
if (!priv || !network || !_expectedAddress) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(priv)) throw new Error('Private key is not valid !');
//Processing
var expectedAddress = _expectedAddress.toUpperCase().replace(/-/g, '');
var kp = _keyPair2.default.create(priv);
var address = _address2.default.toAddress(kp.publicKey.toString(), network);
// Result
return address === expectedAddress;
};
function hashfunc(dest, data, dataLength) {
var convertedData = _convert2.default.ua2words(data, dataLength);
var hash = _cryptoJs2.default.SHA3(convertedData, {
outputLength: 512
});
_convert2.default.words2ua(dest, hash);
}
function key_derive(shared, salt, sk, pk) {
_naclFast2.default.lowlevel.crypto_shared_key_hash(shared, pk, sk, hashfunc);
for (var i = 0; i < salt.length; i++) {
shared[i] ^= salt[i];
}
var hash = _cryptoJs2.default.SHA3(_convert2.default.ua2words(shared, 32), {
outputLength: 256
});
return hash;
}
/**
* Generate a random key
*
* @return {Uint8Array} - A random key
*/
var randomKey = function randomKey() {
var rkey = _naclFast2.default.randomBytes(32);
return rkey;
};
/**
* Encrypt hex data using a key
*
* @param {string} data - An hex string
* @param {Uint8Array} key - An Uint8Array key
*
* @return {object} - The encrypted data
*/
var encrypt = function encrypt(data, key) {
// Errors
if (!data || !key) throw new Error('Missing argument !');
// Processing
var iv = _naclFast2.default.randomBytes(16);
var encKey = _convert2.default.ua2words(key, 32);
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = _cryptoJs2.default.AES.encrypt(_cryptoJs2.default.enc.Hex.parse(data), encKey, encIv);
// Result
return {
ciphertext: encrypted.ciphertext,
iv: iv,
key: key
};
};
/**
* Decrypt data
*
* @param {object} data - An encrypted data object
*
* @return {string} - The decrypted hex string
*/
var decrypt = function decrypt(data) {
// Errors
if (!data) throw new Error('Missing argument !');
// Processing
var encKey = _convert2.default.ua2words(data.key, 32);
var encIv = {
iv: _convert2.default.ua2words(data.iv, 16)
};
// Result
return _cryptoJs2.default.enc.Hex.stringify(_cryptoJs2.default.AES.decrypt(data, encKey, encIv));
};
/**
* Encode a private key using a password
*
* @param {string} privateKey - An hex private key
* @param {string} password - A password
*
* @return {object} - The encoded data
*/
var encodePrivKey = function encodePrivKey(privateKey, password) {
// Errors
if (!privateKey || !password) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
var pass = derivePassSha(password, 20);
var r = encrypt(privateKey, _convert2.default.hex2ua(pass.priv));
// Result
return {
ciphertext: _cryptoJs2.default.enc.Hex.stringify(r.ciphertext),
iv: _convert2.default.ua2hex(r.iv)
};
};
/***
* Encode a message, separated from encode() to help testing
*
* @param {string} senderPriv - A sender private key
* @param {string} recipientPub - A recipient public key
* @param {string} msg - A text message
* @param {Uint8Array} iv - An initialization vector
* @param {Uint8Array} salt - A salt
*
* @return {string} - The encoded message
*/
var _encode = function _encode(senderPriv, recipientPub, msg, iv, salt) {
// Errors
if (!senderPriv || !recipientPub || !msg || !iv || !salt) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!_helpers2.default.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
var sk = _convert2.default.hex2ua_reversed(senderPriv);
var pk = _convert2.default.hex2ua(recipientPub);
var shared = new Uint8Array(32);
var r = key_derive(shared, salt, sk, pk);
var encKey = r;
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = _cryptoJs2.default.AES.encrypt(_cryptoJs2.default.enc.Hex.parse(_convert2.default.utf8ToHex(msg)), encKey, encIv);
// Result
var result = _convert2.default.ua2hex(salt) + _convert2.default.ua2hex(iv) + _cryptoJs2.default.enc.Hex.stringify(encrypted.ciphertext);
return result;
};
/**
* Encode a message
*
* @param {string} senderPriv - A sender private key
* @param {string} recipientPub - A recipient public key
* @param {string} msg - A text message
*
* @return {string} - The encoded message
*/
var encode = function encode(senderPriv, recipientPub, msg) {
// Errors
if (!senderPriv || !recipientPub || !msg) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!_helpers2.default.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
var iv = _naclFast2.default.randomBytes(16);
//console.log("IV:", convert.ua2hex(iv));
var salt = _naclFast2.default.randomBytes(32);
var encoded = _encode(senderPriv, recipientPub, msg, iv, salt);
// Result
return encoded;
};
/**
* Decode an encrypted message payload
*
* @param {string} recipientPrivate - A recipient private key
* @param {string} senderPublic - A sender public key
* @param {string} _payload - An encrypted message payload
*
* @return {string} - The decoded payload as hex
*/
var decode = function decode(recipientPrivate, senderPublic, _payload) {
// Errors
if (!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(recipientPrivate)) throw new Error('Private key is not valid !');
if (!_helpers2.default.isPublicKeyValid(senderPublic)) throw new Error('Public key is not valid !');
// Processing
var binPayload = _convert2.default.hex2ua(_payload);
var salt = new Uint8Array(binPayload.buffer, 0, 32);
var iv = new Uint8Array(binPayload.buffer, 32, 16);
var payload = new Uint8Array(binPayload.buffer, 48);
var sk = _convert2.default.hex2ua_reversed(recipientPrivate);
var pk = _convert2.default.hex2ua(senderPublic);
var shared = new Uint8Array(32);
var r = key_derive(shared, salt, sk, pk);
var encKey = r;
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = {
'ciphertext': _convert2.default.ua2words(payload, payload.length)
};
var plain = _cryptoJs2.default.AES.decrypt(encrypted, encKey, encIv);
// Result
var hexplain = _cryptoJs2.default.enc.Hex.stringify(plain);
return hexplain;
};
module.exports = {
toMobileKey: toMobileKey,
derivePassSha: derivePassSha,
passwordToPrivatekey: passwordToPrivatekey,
checkAddress: checkAddress,
randomKey: randomKey,
decrypt: decrypt,
encrypt: encrypt,
encodePrivKey: encodePrivKey,
_encode: _encode,
encode: encode,
decode: decode
};
},{"../external/nacl-fast":20,"../model/address":23,"../model/network":26,"../utils/convert":49,"../utils/helpers":51,"./keyPair":19,"crypto-js":179}],19:[function(require,module,exports){
'use strict';
var _naclFast = require('../external/nacl-fast');
var _naclFast2 = _interopRequireDefault(_naclFast);
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***
* Create a BinaryKey object
*
* @param {Uint8Array} keyData - A key data
*/
var BinaryKey = function BinaryKey(keyData) {
this.data = keyData;
this.toString = function () {
return _convert2.default.ua2hex(this.data);
};
};
var hashfunc = function hashfunc(dest, data, dataLength) {
var convertedData = _convert2.default.ua2words(data, dataLength);
var hash = _cryptoJs2.default.SHA3(convertedData, {
outputLength: 512
});
_convert2.default.words2ua(dest, hash);
};
/***
* Create an hasher object
*/
var hashobj = function hashobj() {
this.sha3 = _cryptoJs2.default.algo.SHA3.create({
outputLength: 512
});
this.reset = function () {
this.sha3 = _cryptoJs2.default.algo.SHA3.create({
outputLength: 512
});
};
this.update = function (data) {
if (data instanceof BinaryKey) {
var converted = _convert2.default.ua2words(data.data, data.data.length);
var result = _cryptoJs2.default.enc.Hex.stringify(converted);
this.sha3.update(converted);
} else if (data instanceof Uint8Array) {
var _converted = _convert2.default.ua2words(data, data.length);
this.sha3.update(_converted);
} else if (typeof data === "string") {
var _converted2 = _cryptoJs2.default.enc.Hex.parse(data);
this.sha3.update(_converted2);
} else {
throw new Error("unhandled argument");
}
};
this.finalize = function (result) {
var hash = this.sha3.finalize();
_convert2.default.words2ua(result, hash);
};
};
/***
* Create a KeyPair Object
*
* @param {string} privkey - An hex private key
*/
var KeyPair = function KeyPair(privkey) {
var _this = this;
this.publicKey = new BinaryKey(new Uint8Array(_naclFast2.default.lowlevel.crypto_sign_PUBLICKEYBYTES));
this.secretKey = _convert2.default.hex2ua_reversed(privkey);
_naclFast2.default.lowlevel.crypto_sign_keypair_hash(this.publicKey.data, this.secretKey, hashfunc);
// Signature
this.sign = function (data) {
var sig = new Uint8Array(64);
var hasher = new hashobj();
var r = _naclFast2.default.lowlevel.crypto_sign_hash(sig, _this, data, hasher);
if (!r) {
alert("Couldn't sign the tx, generated invalid signature");
throw new Error("Couldn't sign the tx, generated invalid signature");
}
return new BinaryKey(sig);
};
};
/**
* Create a NEM KeyPair
*
* @param {string} hexdata - An hex private key
*
* @return {object} - The NEM KeyPair object
*/
var create = function create(hexdata) {
// Errors
if (!hexdata) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(hexdata)) throw new Error('Private key is not valid !');
// Processing
var r = new KeyPair(hexdata);
// Result
return r;
};
/**
* Verify a signature.
*
* @param {string} publicKey - The public key to use for verification.
* @param {string} data - The data to verify.
* @param {string} signature - The signature to verify.
*
* @return {boolean} - True if the signature is valid, false otherwise.
*/
var verifySignature = function verifySignature(publicKey, data, signature) {
// Errors
if (!publicKey || !data || !signature) throw new Error('Missing argument !');
if (!_helpers2.default.isPublicKeyValid(publicKey)) throw new Error('Public key is not valid !');
if (!_helpers2.default.isHexadecimal(signature)) {
//console.error('Signature must be hexadecimal only !');
return false;
}
if (signature.length !== 128) {
//console.error('Signature length is incorrect !')
return false;
}
// Create an hasher object
var hasher = new hashobj();
// Convert public key to Uint8Array
var _pk = _convert2.default.hex2ua(publicKey);
// Convert signature to Uint8Array
var _signature = _convert2.default.hex2ua(signature);
var c = _naclFast2.default;
var p = [c.gf(), c.gf(), c.gf(), c.gf()];
var q = [c.gf(), c.gf(), c.gf(), c.gf()];
if (c.unpackneg(q, _pk)) return false;
var h = new Uint8Array(64);
hasher.reset();
hasher.update(_signature.subarray(0, 64 / 2));
hasher.update(_pk);
hasher.update(data);
hasher.finalize(h);
c.reduce(h);
c.scalarmult(p, q, h);
var t = new Uint8Array(64);
c.scalarbase(q, _signature.subarray(64 / 2));
c.add(p, q);
c.pack(t, p);
return 0 === _naclFast2.default.lowlevel.crypto_verify_32(_signature, 0, t, 0);
};
module.exports = {
create: create,
verifySignature: verifySignature
};
},{"../external/nacl-fast":20,"../utils/convert":49,"../utils/helpers":51,"crypto-js":179}],20:[function(require,module,exports){
'use strict';
(function (nacl) {
'use strict';
// polyfill for TypedArray.prototype.slice()
Uint8Array.prototype.slice = function (start, end) {
var len = this.length;
var relativeStart = start;
var k = relativeStart < 0 ? max(len + relativeStart, 0) : Math.min(relativeStart, len);
var relativeEnd = end === undefined ? len : end;
var final = relativeEnd < 0 ? max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
var count = final - k;
var c = this.constructor;
var a = new c(count);
var n = 0;
while (k < final) {
a[n] = JSON.parse(JSON.stringify(this[k]));
k++;
n++;
}
return a;
};
Float64Array.prototype.slice = function (start, end) {
var len = this.length;
var relativeStart = start;
var k = relativeStart < 0 ? max(len + relativeStart, 0) : Math.min(relativeStart, len);
var relativeEnd = end === undefined ? len : end;
var final = relativeEnd < 0 ? max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
var count = final - k;
var c = this.constructor;
var a = new c(count);
var n = 0;
while (k < final) {
a[n] = JSON.parse(JSON.stringify(this[k]));
k++;
n++;
}
return a;
};
// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
//
// Implementation derived from TweetNaCl version 20140427.
// See for details: http://tweetnacl.cr.yp.to/
var gf = function gf(init) {
var i,
r = new Float64Array(16);
if (init) for (i = 0; i < init.length; i++) {
r[i] = init[i];
}return r;
};
// Pluggable, initialized in high-level API below.
var randombytes = function randombytes() /* x, n */{
throw new Error('no PRNG');
};
var _0 = new Uint8Array(16);
var _9 = new Uint8Array(32);_9[0] = 9;
var gf0 = gf(),
gf1 = gf([1]),
_121665 = gf([0xdb41, 1]),
D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
function vn(x, xi, y, yi, n) {
var i,
d = 0;
for (i = 0; i < n; i++) {
d |= x[xi + i] ^ y[yi + i];
}return (1 & d - 1 >>> 8) - 1;
}
function crypto_verify_32(x, xi, y, yi) {
return vn(x, xi, y, yi, 32);
}
function set25519(r, a) {
var i;
for (i = 0; i < 16; i++) {
r[i] = a[i] | 0;
}
}
function car25519(o) {
var i,
v,
c = 1;
for (i = 0; i < 16; i++) {
v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function sel25519(p, q, b) {
var t,
c = ~(b - 1);
for (var i = 0; i < 16; i++) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o, n) {
var i, j, b;
var m = gf(),
t = gf();
for (i = 0; i < 16; i++) {
t[i] = n[i];
}car25519(t);
car25519(t);
car25519(t);
for (j = 0; j < 2; j++) {
m[0] = t[0] - 0xffed;
for (i = 1; i < 15; i++) {
m[i] = t[i] - 0xffff - (m[i - 1] >> 16 & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - (m[14] >> 16 & 1);
b = m[15] >> 16 & 1;
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for (i = 0; i < 16; i++) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function neq25519(a, b) {
var c = new Uint8Array(32),
d = new Uint8Array(32);
pack25519(c, a);
pack25519(d, b);
return crypto_verify_32(c, 0, d, 0);
}
function par25519(a) {
var d = new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function unpack25519(o, n) {
var i;
for (i = 0; i < 16; i++) {
o[i] = n[2 * i] + (n[2 * i + 1] << 8);
}o[15] &= 0x7fff;
}
function A(o, a, b) {
for (var i = 0; i < 16; i++) {
o[i] = a[i] + b[i];
}
}
function Z(o, a, b) {
for (var i = 0; i < 16; i++) {
o[i] = a[i] - b[i];
}
}
function M(o, a, b) {
var v,
c,
t0 = 0,
t1 = 0,
t2 = 0,
t3 = 0,
t4 = 0,
t5 = 0,
t6 = 0,
t7 = 0,
t8 = 0,
t9 = 0,
t10 = 0,
t11 = 0,
t12 = 0,
t13 = 0,
t14 = 0,
t15 = 0,
t16 = 0,
t17 = 0,
t18 = 0,
t19 = 0,
t20 = 0,
t21 = 0,
t22 = 0,
t23 = 0,
t24 = 0,
t25 = 0,
t26 = 0,
t27 = 0,
t28 = 0,
t29 = 0,
t30 = 0,
b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11],
b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is