1
0
mirror of https://github.com/bigchaindb/js-bigchaindb-driver.git synced 2024-11-22 09:46:58 +01:00

rebuild + add node dist

This commit is contained in:
diminator 2017-05-10 09:36:07 +02:00
parent 0098a58545
commit aefd868566
No known key found for this signature in database
GPG Key ID: C3D8590E6D0D439A
35 changed files with 1641 additions and 80 deletions

200
dist/bundle/bundle.js vendored

File diff suppressed because one or more lines are too long

43
dist/node/Ed25519Keypair.js vendored Normal file
View File

@ -0,0 +1,43 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Ed25519Keypair;
var _bs = require('bs58');
var _bs2 = _interopRequireDefault(_bs);
var _tweetnacl = require('tweetnacl');
var _tweetnacl2 = _interopRequireDefault(_tweetnacl);
var _jsSha = require('js-sha3');
var _jsSha2 = _interopRequireDefault(_jsSha);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @class Keypair Ed25519 keypair in base58 (as BigchainDB expects base58 keys)
* @type {Object}
* @param {number} [secret] A seed that will be used as a key derivation function
* @property {string} publicKey
* @property {string} privateKey
*/
function Ed25519Keypair(secret) {
var keyPair = void 0;
if (secret) {
// Quick and dirty: use key derivation function instead
var secretHash = _jsSha2.default.sha3_256.create().update(secret).array();
keyPair = _tweetnacl2.default.sign.keyPair.fromSeed(new Uint8Array(secretHash));
} else {
keyPair = _tweetnacl2.default.sign.keyPair();
}
this.publicKey = _bs2.default.encode(keyPair.publicKey);
// tweetnacl's generated secret key is the secret key + public key (resulting in a 64-byte buffer)
this.privateKey = _bs2.default.encode(keyPair.secretKey.slice(0, 32));
}
module.exports = exports['default'];

106
dist/node/baseRequest.js vendored Normal file
View File

@ -0,0 +1,106 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = baseRequest;
var _es6Promise = require('es6-promise');
var _fetchPonyfill = require('fetch-ponyfill');
var _fetchPonyfill2 = _interopRequireDefault(_fetchPonyfill);
var _sprintfJs = require('sprintf-js');
var _format_text = require('./format_text');
var _format_text2 = _interopRequireDefault(_format_text);
var _stringify_as_query_param = require('./stringify_as_query_param');
var _stringify_as_query_param2 = _interopRequireDefault(_stringify_as_query_param);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var fetch = (0, _fetchPonyfill2.default)(_es6Promise.Promise);
/**
* imported from https://github.com/bigchaindb/js-utility-belt/
*
* Global fetch wrapper that adds some basic error handling and ease of use enhancements.
* Considers any non-2xx response as an error.
*
* For more information on fetch, see https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch.
*
* Expects fetch to already be available (either in a ES6 environment, bundled through webpack, or
* injected through a polyfill).
*
* @param {string} url Url to request. Can be specified as a sprintf format string (see
* https://github.com/alexei/sprintf.js) that will be resolved using
* `config.urlTemplateSpec`.
* @param {object} config Additional configuration, mostly passed to fetch as its 'init' config
* (see https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters).
* @param {*} config.jsonBody Json payload to the request. Will automatically be
* JSON.stringify()-ed and override `config.body`.
* @param {string|object} config.query Query parameter to append to the end of the url.
* If specified as an object, keys will be
* decamelized into snake case first.
* @param {*[]|object} config.urlTemplateSpec Format spec to use to expand the url (see sprintf).
* @param {*} config.* All other options are passed through to fetch.
*
* @return {Promise} Promise that will resolve with the response if its status was 2xx;
* otherwise rejects with the response
*/
function baseRequest(url) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var jsonBody = _ref.jsonBody,
query = _ref.query,
urlTemplateSpec = _ref.urlTemplateSpec,
fetchConfig = _objectWithoutProperties(_ref, ['jsonBody', 'query', 'urlTemplateSpec']);
var expandedUrl = url;
if (urlTemplateSpec != null) {
if (Array.isArray(urlTemplateSpec) && urlTemplateSpec.length) {
// Use vsprintf for the array call signature
expandedUrl = (0, _sprintfJs.vsprintf)(url, urlTemplateSpec);
} else if (urlTemplateSpec && (typeof urlTemplateSpec === 'undefined' ? 'undefined' : _typeof(urlTemplateSpec)) === 'object' && Object.keys(urlTemplateSpec).length) {
expandedUrl = (0, _format_text2.default)(url, urlTemplateSpec);
} else if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('Supplied urlTemplateSpec was not an array or object. Ignoring...');
}
}
if (query != null) {
if (typeof query === 'string') {
expandedUrl += query;
} else if (query && (typeof query === 'undefined' ? 'undefined' : _typeof(query)) === 'object') {
expandedUrl += (0, _stringify_as_query_param2.default)(query);
} else if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('Supplied query was not a string or object. Ignoring...');
}
}
if (jsonBody != null) {
fetchConfig.body = JSON.stringify(jsonBody);
}
return fetch.fetch(expandedUrl, fetchConfig).then(function (res) {
// If status is not a 2xx (based on Response.ok), assume it's an error
// See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
if (!(res && res.ok)) {
throw res;
}
return res;
});
}
module.exports = exports['default'];

18
dist/node/connection/getApiUrls.js vendored Normal file
View File

@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getApiUrls;
function getApiUrls(API_PATH) {
return {
'blocks': API_PATH + 'blocks',
'blocks_detail': API_PATH + 'blocks/%(blockId)s',
'outputs': API_PATH + 'outputs',
'statuses': API_PATH + 'statuses',
'transactions': API_PATH + 'transactions',
'transactions_detail': API_PATH + 'transactions/%(txId)s',
'votes': API_PATH + 'votes'
};
}
module.exports = exports['default'];

30
dist/node/connection/getBlock.js vendored Normal file
View File

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getBlock;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param blockId
* @param API_PATH
*/
function getBlock(blockId, API_PATH) {
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['blocks_detail'], {
urlTemplateSpec: {
blockId: blockId
}
});
}
module.exports = exports['default'];

30
dist/node/connection/getStatus.js vendored Normal file
View File

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getStatus;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param tx_id
* @param API_PATH
*/
function getStatus(tx_id, API_PATH) {
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['statuses'], {
query: {
tx_id: tx_id
}
});
}
module.exports = exports['default'];

30
dist/node/connection/getTransaction.js vendored Normal file
View File

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getTransaction;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param txId
* @param API_PATH
*/
function getTransaction(txId, API_PATH) {
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['transactions_detail'], {
urlTemplateSpec: {
txId: txId
}
});
}
module.exports = exports['default'];

54
dist/node/connection/index.js vendored Normal file
View File

@ -0,0 +1,54 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.postTransaction = exports.pollStatusAndFetchTransaction = exports.listVotes = exports.listTransactions = exports.listOutputs = exports.listBlocks = exports.getStatus = exports.getTransaction = exports.getBlock = undefined;
var _getBlock2 = require('./getBlock');
var _getBlock3 = _interopRequireDefault(_getBlock2);
var _getTransaction2 = require('./getTransaction');
var _getTransaction3 = _interopRequireDefault(_getTransaction2);
var _getStatus2 = require('./getStatus');
var _getStatus3 = _interopRequireDefault(_getStatus2);
var _listBlocks2 = require('./listBlocks');
var _listBlocks3 = _interopRequireDefault(_listBlocks2);
var _listOutputs2 = require('./listOutputs');
var _listOutputs3 = _interopRequireDefault(_listOutputs2);
var _listTransactions2 = require('./listTransactions');
var _listTransactions3 = _interopRequireDefault(_listTransactions2);
var _listVotes2 = require('./listVotes');
var _listVotes3 = _interopRequireDefault(_listVotes2);
var _pollStatusAndFetchTransaction2 = require('./pollStatusAndFetchTransaction');
var _pollStatusAndFetchTransaction3 = _interopRequireDefault(_pollStatusAndFetchTransaction2);
var _postTransaction2 = require('./postTransaction');
var _postTransaction3 = _interopRequireDefault(_postTransaction2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.getBlock = _getBlock3.default;
exports.getTransaction = _getTransaction3.default;
exports.getStatus = _getStatus3.default;
exports.listBlocks = _listBlocks3.default;
exports.listOutputs = _listOutputs3.default;
exports.listTransactions = _listTransactions3.default;
exports.listVotes = _listVotes3.default;
exports.pollStatusAndFetchTransaction = _pollStatusAndFetchTransaction3.default;
exports.postTransaction = _postTransaction3.default;

35
dist/node/connection/listBlocks.js vendored Normal file
View File

@ -0,0 +1,35 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = listBlocks;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param tx_id
* @param status
* @param API_PATH
*/
function listBlocks(_ref, API_PATH) {
var tx_id = _ref.tx_id,
status = _ref.status;
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['blocks'], {
query: {
tx_id: tx_id,
status: status
}
});
}
module.exports = exports['default'];

37
dist/node/connection/listOutputs.js vendored Normal file
View File

@ -0,0 +1,37 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = listOutputs;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param public_key
* @param unspent
* @param API_PATH
* @param onlyJsonResponse
*/
function listOutputs(_ref, API_PATH) {
var public_key = _ref.public_key,
unspent = _ref.unspent;
var onlyJsonResponse = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['outputs'], {
query: {
public_key: public_key,
unspent: unspent
}
}, onlyJsonResponse);
}
module.exports = exports['default'];

View File

@ -0,0 +1,35 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = listTransactions;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param asset_id
* @param operation
* @param API_PATH
*/
function listTransactions(_ref, API_PATH) {
var asset_id = _ref.asset_id,
operation = _ref.operation;
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['transactions'], {
query: {
asset_id: asset_id,
operation: operation
}
});
}
module.exports = exports['default'];

30
dist/node/connection/listVotes.js vendored Normal file
View File

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = listVotes;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* @param block_id
* @param API_PATH
*/
function listVotes(block_id, API_PATH) {
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['votes'], {
query: {
block_id: block_id
}
});
}
module.exports = exports['default'];

View File

@ -0,0 +1,44 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (tx_id, API_PATH) {
return new Promise(function (resolve, reject) {
var timer = setInterval(function () {
(0, _getStatus2.default)(tx_id, API_PATH).then(function (res) {
console.log('Fetched transaction status:', res);
if (res.status === 'valid') {
clearInterval(timer);
(0, _getTransaction2.default)(tx_id, API_PATH).then(function (res) {
console.log('Fetched transaction:', res);
resolve(res);
});
}
}).catch(function (err) {
clearInterval(timer);
reject(err);
});
}, 500);
});
};
var _getTransaction = require('./getTransaction');
var _getTransaction2 = _interopRequireDefault(_getTransaction);
var _getStatus = require('./getStatus');
var _getStatus2 = _interopRequireDefault(_getStatus);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default'];
/**
* @public
* @param tx_id
* @param API_PATH
* @return {Promise}
*/

30
dist/node/connection/postTransaction.js vendored Normal file
View File

@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = postTransaction;
var _getApiUrls = require('./getApiUrls');
var _getApiUrls2 = _interopRequireDefault(_getApiUrls);
var _request = require('../request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
*
* @param transaction
* @param API_PATH
*/
function postTransaction(transaction, API_PATH) {
return (0, _request2.default)((0, _getApiUrls2.default)(API_PATH)['transactions'], {
method: 'POST',
jsonBody: transaction
});
}
module.exports = exports['default'];

109
dist/node/format_text.js vendored Normal file
View File

@ -0,0 +1,109 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = formatText;
var _sprintfJs = require('sprintf-js');
// Regexes taken from or inspired by sprintf-js
var Regex = {
TEMPLATE_LITERAL: /\${([^\)]+?)}/g,
KEY: /^([a-z_][a-z_\d]*)/i,
KEY_ACCESS: /^\.([a-z_][a-z_\d]*)/i,
INDEX_ACCESS: /^\[(\d+)\]/
};
/**
* imported from https://github.com/bigchaindb/js-utility-belt/
*
* Formats strings similarly to C's sprintf, with the addition of '${...}' formats.
*
* Makes a first pass replacing '${...}' formats before passing the expanded string and other
* arguments to sprintf-js. For more information on what sprintf can do, see
* https://github.com/alexei/sprintf.js.
*
* Examples:
* formatText('Hi there ${dimi}!', { dimi: 'Dimi' })
* => 'Hi there Dimi!'
*
* formatText('${database} is %(status)s', { database: 'BigchainDB', status: 'big' })
* => 'BigchainDB is big'
*
* Like sprintf-js, string interpolation for keywords and indexes is supported too:
* formatText('Berlin is best known for its ${berlin.topKnownFor[0].name}', {
* berlin: {
* topKnownFor: [{
* name: 'Currywurst'
* }, ...
* ]
* }
* })
* => 'Berlin is best known for its Currywurst'
*/
function formatText(s) {
var expandedFormatStr = s;
// Try to replace formats of the form '${...}' if named replacement fields are used
for (var _len = arguments.length, argv = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
argv[_key - 1] = arguments[_key];
}
if (s && argv.length === 1 && _typeof(argv[0]) === 'object') {
var templateSpecObj = argv[0];
expandedFormatStr = s.replace(Regex.TEMPLATE_LITERAL, function (match, replacement) {
var interpolationLeft = replacement;
/**
* Interpolation algorithm inspired by sprintf-js.
*
* Goes through the replacement string getting the left-most key or index to interpolate
* on each pass. `value` at each step holds the last interpolation result, `curMatch` is
* the current property match, and `interpolationLeft` is the portion of the replacement
* string still to be interpolated.
*
* It's useful to note that RegExp.exec() returns with an array holding:
* [0]: Full string matched
* [1+]: Matching groups
*
* And that in the regexes defined, the first matching group always corresponds to the
* property matched.
*/
var value = void 0;
var curMatch = Regex.KEY.exec(interpolationLeft);
if (curMatch !== null) {
value = templateSpecObj[curMatch[1]];
// Assigning in the conditionals here makes the code less bloated
/* eslint-disable no-cond-assign */
while ((interpolationLeft = interpolationLeft.substring(curMatch[0].length)) && value != null) {
if (curMatch = Regex.KEY_ACCESS.exec(interpolationLeft)) {
value = value[curMatch[1]];
} else if (curMatch = Regex.INDEX_ACCESS.exec(interpolationLeft)) {
value = value[curMatch[1]];
} else {
break;
}
}
/* eslint-enable no-cond-assign */
}
// If there's anything left to interpolate by the end then we've failed to interpolate
// the entire replacement string.
if (interpolationLeft.length) {
throw new SyntaxError('[formatText] failed to parse named argument key: ' + replacement);
}
return value;
});
}
return _sprintfJs.sprintf.apply(undefined, [expandedFormatStr].concat(argv));
}
module.exports = exports['default'];

61
dist/node/request.js vendored Normal file
View File

@ -0,0 +1,61 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = request;
var _baseRequest = require('./baseRequest');
var _baseRequest2 = _interopRequireDefault(_baseRequest);
var _sanitize = require('./sanitize');
var _sanitize2 = _interopRequireDefault(_sanitize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_REQUEST_CONFIG = {
credentials: 'include',
headers: {
'Accept': 'application/json'
}
};
/**
* Small wrapper around js-utility-belt's request that provides url resolving, default settings, and
* response handling.
*/
function request(url) {
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var onlyJsonResponse = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
// Load default fetch configuration and remove any falsy query parameters
var requestConfig = _extends({}, DEFAULT_REQUEST_CONFIG, config, {
query: config.query && (0, _sanitize2.default)(config.query)
});
var apiUrl = url;
if (requestConfig.jsonBody) {
requestConfig.headers = _extends({}, requestConfig.headers, {
'Content-Type': 'application/json'
});
}
if (!url) {
return Promise.reject(new Error('Request was not given a url.'));
}
return (0, _baseRequest2.default)(apiUrl, requestConfig).then(function (res) {
return onlyJsonResponse ? res.json() : {
json: res.json(),
url: res.url
};
}).catch(function (err) {
console.error(err);
throw err;
});
}
module.exports = exports['default'];

97
dist/node/sanitize.js vendored Normal file
View File

@ -0,0 +1,97 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = sanitize;
var _includes = require('core-js/library/fn/array/includes');
var _includes2 = _interopRequireDefault(_includes);
var _entries = require('core-js/library/fn/object/entries');
var _entries2 = _interopRequireDefault(_entries);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Abstraction for selectFromObject and omitFromObject for DRYness.
* Set isInclusion to true if the filter should be for including the filtered items (ie. selecting
* only them vs omitting only them).
*/
function filterFromObject(obj, filter) {
var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
_ref$isInclusion = _ref.isInclusion,
isInclusion = _ref$isInclusion === undefined ? true : _ref$isInclusion;
if (filter && Array.isArray(filter)) {
return applyFilterOnObject(obj, isInclusion ? function (_, key) {
return (0, _includes2.default)(filter, key);
} : function (_, key) {
return !(0, _includes2.default)(filter, key);
});
} else if (filter && typeof filter === 'function') {
// Flip the filter fn's return if it's for inclusion
return applyFilterOnObject(obj, isInclusion ? filter : function () {
return !filter.apply(undefined, arguments);
});
} else {
throw new Error('The given filter is not an array or function. Exclude aborted');
}
}
/**
* Returns a filtered copy of the given object's own enumerable properties (no inherited
* properties), keeping any keys that pass the given filter function.
*/
function applyFilterOnObject(obj, filterFn) {
if (filterFn == null) {
return _extends({}, obj);
}
var filteredObj = {};
(0, _entries2.default)(obj).forEach(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
key = _ref3[0],
val = _ref3[1];
if (filterFn(val, key)) {
filteredObj[key] = val;
}
});
return filteredObj;
}
/**
* Similar to lodash's _.pick(), this returns a copy of the given object's
* own and inherited enumerable properties, selecting only the keys in
* the given array or whose value pass the given filter function.
* @param {object} obj Source object
* @param {array|function} filter Array of key names to select or function to invoke per iteration
* @return {object} The new object
*/
function selectFromObject(obj, filter) {
return filterFromObject(obj, filter);
}
/**
* Glorified selectFromObject. Takes an object and returns a filtered shallow copy that strips out
* any properties that are falsy (including coercions, ie. undefined, null, '', 0, ...).
* Does not modify the passed in object.
*
* @param {object} obj Javascript object
* @return {object} Sanitized Javascript object
*/
function sanitize(obj) {
return selectFromObject(obj, function (val) {
return !!val;
});
}
module.exports = exports['default'];

17
dist/node/sha256Hash.js vendored Normal file
View File

@ -0,0 +1,17 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = sha256Hash;
var _jsSha = require('js-sha3');
var _jsSha2 = _interopRequireDefault(_jsSha);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function sha256Hash(data) {
return _jsSha2.default.sha3_256.create().update(data).hex();
}
module.exports = exports['default'];

70
dist/node/stringify_as_query_param.js vendored Normal file
View File

@ -0,0 +1,70 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = stringifyAsQueryParam;
var _entries = require('core-js/library/fn/object/entries');
var _entries2 = _interopRequireDefault(_entries);
var _decamelize = require('decamelize');
var _decamelize2 = _interopRequireDefault(_decamelize);
var _queryString = require('query-string');
var _queryString2 = _interopRequireDefault(_queryString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* imported from https://github.com/bigchaindb/js-utility-belt/
*
* Takes a key-value dictionary (ie. object) and converts it to a query-parameter string that you
* can directly append into a URL.
*
* Extends queryString.stringify by allowing you to specify a `transform` function that will be
* invoked on each of the dictionary's keys before being stringified into the query-parameter
* string.
*
* By default `transform` is `decamelize`, so a dictionary of the form:
*
* {
* page: 1,
* pageSize: 10
* }
*
* will be converted to a string like:
*
* ?page=1&page_size=10
*
* @param {object} obj Query params dictionary
* @param {function} [transform=decamelize] Transform function for each of the param keys
* @return {string} Query param string
*/
function stringifyAsQueryParam(obj) {
var transform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _decamelize2.default;
if (!obj || (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || !Object.keys(obj).length) {
return '';
}
var transformedKeysObj = (0, _entries2.default)(obj).reduce(function (paramsObj, _ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
paramsObj[transform(key)] = value;
return paramsObj;
}, {});
return '?' + _queryString2.default.stringify(transformedKeysObj);
}
module.exports = exports['default'];

View File

@ -0,0 +1,28 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.default = hashTransaction;
var _serializeTransactionIntoCanonicalString = require('./serializeTransactionIntoCanonicalString');
var _serializeTransactionIntoCanonicalString2 = _interopRequireDefault(_serializeTransactionIntoCanonicalString);
var _sha256Hash = require('../sha256Hash');
var _sha256Hash2 = _interopRequireDefault(_sha256Hash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function hashTransaction(transaction) {
// Safely remove any tx id from the given transaction for hashing
var tx = _extends({}, transaction);
delete tx.id;
return (0, _sha256Hash2.default)((0, _serializeTransactionIntoCanonicalString2.default)(tx));
}
module.exports = exports['default'];

64
dist/node/transaction/index.js vendored Normal file
View File

@ -0,0 +1,64 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ccJsonify = exports.ccJsonLoad = exports.signTransaction = exports.serializeTransactionIntoCanonicalString = exports.makeTransferTransaction = exports.makeTransaction = exports.makeOutput = exports.makeCreateTransaction = exports.makeThresholdCondition = exports.makeSha256Condition = exports.makeEd25519Condition = undefined;
var _makeEd25519Condition2 = require('./makeEd25519Condition');
var _makeEd25519Condition3 = _interopRequireDefault(_makeEd25519Condition2);
var _makeSha256Condition2 = require('./makeSha256Condition');
var _makeSha256Condition3 = _interopRequireDefault(_makeSha256Condition2);
var _makeThresholdCondition2 = require('./makeThresholdCondition');
var _makeThresholdCondition3 = _interopRequireDefault(_makeThresholdCondition2);
var _makeCreateTransaction2 = require('./makeCreateTransaction');
var _makeCreateTransaction3 = _interopRequireDefault(_makeCreateTransaction2);
var _makeOutput2 = require('./makeOutput');
var _makeOutput3 = _interopRequireDefault(_makeOutput2);
var _makeTransaction2 = require('./makeTransaction');
var _makeTransaction3 = _interopRequireDefault(_makeTransaction2);
var _makeTransferTransaction2 = require('./makeTransferTransaction');
var _makeTransferTransaction3 = _interopRequireDefault(_makeTransferTransaction2);
var _serializeTransactionIntoCanonicalString2 = require('./serializeTransactionIntoCanonicalString');
var _serializeTransactionIntoCanonicalString3 = _interopRequireDefault(_serializeTransactionIntoCanonicalString2);
var _signTransaction2 = require('./signTransaction');
var _signTransaction3 = _interopRequireDefault(_signTransaction2);
var _ccJsonLoad2 = require('./utils/ccJsonLoad');
var _ccJsonLoad3 = _interopRequireDefault(_ccJsonLoad2);
var _ccJsonify2 = require('./utils/ccJsonify');
var _ccJsonify3 = _interopRequireDefault(_ccJsonify2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.makeEd25519Condition = _makeEd25519Condition3.default;
exports.makeSha256Condition = _makeSha256Condition3.default;
exports.makeThresholdCondition = _makeThresholdCondition3.default;
exports.makeCreateTransaction = _makeCreateTransaction3.default;
exports.makeOutput = _makeOutput3.default;
exports.makeTransaction = _makeTransaction3.default;
exports.makeTransferTransaction = _makeTransferTransaction3.default;
exports.serializeTransactionIntoCanonicalString = _serializeTransactionIntoCanonicalString3.default;
exports.signTransaction = _signTransaction3.default;
exports.ccJsonLoad = _ccJsonLoad3.default;
exports.ccJsonify = _ccJsonify3.default;

View File

@ -0,0 +1,52 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeCreateTransaction;
var _makeInputTemplate = require('./makeInputTemplate');
var _makeInputTemplate2 = _interopRequireDefault(_makeInputTemplate);
var _makeTransaction = require('./makeTransaction');
var _makeTransaction2 = _interopRequireDefault(_makeTransaction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Generate a `CREATE` transaction holding the `asset`, `metadata`, and `outputs`, to be signed by
* the `issuers`.
* @param {object} asset Created asset's data
* @param {object} metadata Metadata for the Transaction
* @param {object[]} outputs Array of Output objects to add to the Transaction.
* Think of these as the recipients of the asset after the transaction.
* For `CREATE` Transactions, this should usually just be a list of
* Outputs wrapping Ed25519 Conditions generated from the issuers' public
* keys (so that the issuers are the recipients of the created asset).
* @param {...string[]} issuers Public key of one or more issuers to the asset being created by this
* Transaction.
* Note: Each of the private keys corresponding to the given public
* keys MUST be used later (and in the same order) when signing the
* Transaction (`signTransaction()`).
* @returns {object} Unsigned transaction -- make sure to call signTransaction() on it before
* sending it off!
*/
function makeCreateTransaction(asset, metadata, outputs) {
var assetDefinition = {
'data': asset || null
};
for (var _len = arguments.length, issuers = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
issuers[_key - 3] = arguments[_key];
}
var inputs = issuers.map(function (issuer) {
return (0, _makeInputTemplate2.default)([issuer]);
});
return (0, _makeTransaction2.default)('CREATE', assetDefinition, metadata, outputs, inputs);
}
module.exports = exports['default'];

View File

@ -0,0 +1,45 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeEd25519Condition;
var _buffer = require('buffer');
var _bs = require('bs58');
var _bs2 = _interopRequireDefault(_bs);
var _fiveBellsCondition = require('five-bells-condition');
var _fiveBellsCondition2 = _interopRequireDefault(_fiveBellsCondition);
var _ccJsonify = require('./utils/ccJsonify');
var _ccJsonify2 = _interopRequireDefault(_ccJsonify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Create an Ed25519 Cryptocondition from an Ed25519 public key to put into an Output of a Transaction
* @param {string} publicKey base58 encoded Ed25519 public key for the recipient of the Transaction
* @param {boolean} [json=true] If true returns a json object otherwise a crypto-condition type
* @returns {object} Ed25519 Condition (that will need to wrapped in an Output)
*/
function makeEd25519Condition(publicKey) {
var json = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var publicKeyBuffer = new _buffer.Buffer(_bs2.default.decode(publicKey));
var ed25519Fulfillment = new _fiveBellsCondition2.default.Ed25519();
ed25519Fulfillment.setPublicKey(publicKeyBuffer);
if (json) {
return (0, _ccJsonify2.default)(ed25519Fulfillment);
}
return ed25519Fulfillment;
}
module.exports = exports['default'];

View File

@ -0,0 +1,18 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeInputTemplate;
function makeInputTemplate() {
var publicKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var fulfills = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var fulfillment = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return {
fulfillment: fulfillment,
fulfills: fulfills,
'owners_before': publicKeys
};
}
module.exports = exports['default'];

24
dist/node/transaction/makeOutput.js vendored Normal file
View File

@ -0,0 +1,24 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeOutput;
/**
* @public
* Create an Output from a Condition.
* Note: Assumes the given Condition was generated from a single public key (e.g. a Ed25519 Condition)
* @param {object} condition Condition (e.g. a Ed25519 Condition from `makeEd25519Condition()`)
* @param {number} amount Amount of the output
* @returns {object} An Output usable in a Transaction
*/
function makeOutput(condition) {
var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return {
amount: JSON.stringify(amount),
condition: condition,
'public_keys': condition.details.hasOwnProperty('public_key') ? [condition.details.public_key] : []
};
}
module.exports = exports['default'];

View File

@ -0,0 +1,38 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeSha256Condition;
var _buffer = require('buffer');
var _fiveBellsCondition = require('five-bells-condition');
var _fiveBellsCondition2 = _interopRequireDefault(_fiveBellsCondition);
var _ccJsonify = require('./utils/ccJsonify');
var _ccJsonify2 = _interopRequireDefault(_ccJsonify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Create a Preimage-Sha256 Cryptocondition from a secret to put into an Output of a Transaction
* @param {string} preimage Preimage to be hashed and wrapped in a crypto-condition
* @param {boolean} [json=true] If true returns a json object otherwise a crypto-condition type
* @returns {object} Preimage-Sha256 Condition (that will need to wrapped in an Output)
*/
function makeSha256Condition(preimage) {
var json = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var sha256Fulfillment = new _fiveBellsCondition2.default.PreimageSha256();
sha256Fulfillment.preimage = new _buffer.Buffer(preimage);
if (json) {
return (0, _ccJsonify2.default)(sha256Fulfillment);
}
return sha256Fulfillment;
}
module.exports = exports['default'];

View File

@ -0,0 +1,44 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeThresholdCondition;
var _fiveBellsCondition = require('five-bells-condition');
var _fiveBellsCondition2 = _interopRequireDefault(_fiveBellsCondition);
var _ccJsonify = require('./utils/ccJsonify');
var _ccJsonify2 = _interopRequireDefault(_ccJsonify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Create an Sha256 Threshold Cryptocondition from threshold to put into an Output of a Transaction
* @param {number} threshold
* @param {Array} [subconditions=[]]
* @param {boolean} [json=true] If true returns a json object otherwise a crypto-condition type
* @returns {object} Sha256 Threshold Condition (that will need to wrapped in an Output)
*/
function makeThresholdCondition(threshold) {
var subconditions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var thresholdCondition = new _fiveBellsCondition2.default.ThresholdSha256();
thresholdCondition.threshold = threshold;
subconditions.forEach(function (subcondition) {
// TODO: add support for Condition and URIs
thresholdCondition.addSubfulfillment(subcondition);
});
if (json) {
return (0, _ccJsonify2.default)(thresholdCondition);
}
return thresholdCondition;
}
module.exports = exports['default'];

View File

@ -0,0 +1,42 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeTransaction;
var _hashTransaction = require('./hashTransaction');
var _hashTransaction2 = _interopRequireDefault(_hashTransaction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeTransactionTemplate() {
return {
'id': null,
'operation': null,
'outputs': [],
'inputs': [],
'metadata': null,
'asset': null,
'version': '0.9'
};
}
function makeTransaction(operation, asset) {
var metadata = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var outputs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
var inputs = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
var tx = makeTransactionTemplate();
tx.operation = operation;
tx.asset = asset;
tx.metadata = metadata;
tx.inputs = inputs;
tx.outputs = outputs;
// Hashing must be done after, as the hash is of the Transaction (up to now)
tx.id = (0, _hashTransaction2.default)(tx);
return tx;
}
module.exports = exports['default'];

View File

@ -0,0 +1,59 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeTransferTransaction;
var _makeInputTemplate = require('./makeInputTemplate');
var _makeInputTemplate2 = _interopRequireDefault(_makeInputTemplate);
var _makeTransaction = require('./makeTransaction');
var _makeTransaction2 = _interopRequireDefault(_makeTransaction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Generate a `TRANSFER` transaction holding the `asset`, `metadata`, and `outputs`, that fulfills
* the `fulfilledOutputs` of `unspentTransaction`.
* @param {object} unspentTransaction Previous Transaction you have control over (i.e. can fulfill
* its Output Condition)
* @param {object} metadata Metadata for the Transaction
* @param {object[]} outputs Array of Output objects to add to the Transaction.
* Think of these as the recipients of the asset after the transaction.
* For `TRANSFER` Transactions, this should usually just be a list of
* Outputs wrapping Ed25519 Conditions generated from the public keys of
* the recipients.
* @param {...number} fulfilledOutputs Indices of the Outputs in `unspentTransaction` that this
* Transaction fulfills.
* Note that the public keys listed in the fulfilled Outputs
* must be used (and in the same order) to sign the Transaction
* (`signTransaction()`).
* @returns {object} Unsigned transaction -- make sure to call signTransaction() on it before
* sending it off!
*/
function makeTransferTransaction(unspentTransaction, metadata, outputs) {
for (var _len = arguments.length, fulfilledOutputs = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
fulfilledOutputs[_key - 3] = arguments[_key];
}
var inputs = fulfilledOutputs.map(function (outputIndex) {
var fulfilledOutput = unspentTransaction.outputs[outputIndex];
var transactionLink = {
'output': outputIndex,
'txid': unspentTransaction.id
};
return (0, _makeInputTemplate2.default)(fulfilledOutput.public_keys, transactionLink);
});
var assetLink = {
'id': unspentTransaction.operation === 'CREATE' ? unspentTransaction.id : unspentTransaction.asset.id
};
return (0, _makeTransaction2.default)('TRANSFER', assetLink, metadata, outputs, inputs);
}
module.exports = exports['default'];

View File

@ -0,0 +1,33 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = serializeTransactionIntoCanonicalString;
var _jsonStableStringify = require('json-stable-stringify');
var _jsonStableStringify2 = _interopRequireDefault(_jsonStableStringify);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Canonically serializes a transaction into a string by sorting the keys
* @param {object} (transaction)
* @return {string} a canonically serialized Transaction
*/
function serializeTransactionIntoCanonicalString(transaction) {
// BigchainDB signs fulfillments by serializing transactions into a "canonical" format where
var tx = (0, _clone2.default)(transaction);
// TODO: set fulfillments to null
// Sort the keys
return (0, _jsonStableStringify2.default)(tx, function (a, b) {
return a.key > b.key ? 1 : -1;
});
}
module.exports = exports['default'];

View File

@ -0,0 +1,59 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = signTransaction;
var _buffer = require('buffer');
var _bs = require('bs58');
var _bs2 = _interopRequireDefault(_bs);
var _fiveBellsCondition = require('five-bells-condition');
var _fiveBellsCondition2 = _interopRequireDefault(_fiveBellsCondition);
var _clone = require('clone');
var _clone2 = _interopRequireDefault(_clone);
var _serializeTransactionIntoCanonicalString = require('./serializeTransactionIntoCanonicalString');
var _serializeTransactionIntoCanonicalString2 = _interopRequireDefault(_serializeTransactionIntoCanonicalString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Sign the given `transaction` with the given `privateKey`s, returning a new copy of `transaction`
* that's been signed.
* Note: Only generates Ed25519 Fulfillments. Thresholds and other types of Fulfillments are left as
* an exercise for the user.
* @param {object} transaction Transaction to sign. `transaction` is not modified.
* @param {...string} privateKeys Private keys associated with the issuers of the `transaction`.
* Looped through to iteratively sign any Input Fulfillments found in
* the `transaction`.
* @returns {object} The signed version of `transaction`.
*/
function signTransaction(transaction) {
for (var _len = arguments.length, privateKeys = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
privateKeys[_key - 1] = arguments[_key];
}
var signedTx = (0, _clone2.default)(transaction);
signedTx.inputs.forEach(function (input, index) {
var privateKey = privateKeys[index];
var privateKeyBuffer = new _buffer.Buffer(_bs2.default.decode(privateKey));
var serializedTransaction = (0, _serializeTransactionIntoCanonicalString2.default)(transaction);
var ed25519Fulfillment = new _fiveBellsCondition2.default.Ed25519();
ed25519Fulfillment.sign(new _buffer.Buffer(serializedTransaction), privateKeyBuffer);
var fulfillmentUri = ed25519Fulfillment.serializeUri();
input.fulfillment = fulfillmentUri;
});
return signedTx;
}
module.exports = exports['default'];

View File

@ -0,0 +1,60 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ccJsonLoad;
var _bs = require('bs58');
var _bs2 = _interopRequireDefault(_bs);
var _fiveBellsCondition = require('five-bells-condition');
var _fiveBellsCondition2 = _interopRequireDefault(_fiveBellsCondition);
var _buffer = require('buffer');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Loads a crypto-condition class (Fulfillment or Condition) from a BigchainDB JSON object
* @param {object} conditionJson
* @returns {cc.Condition} Ed25519 Condition (that will need to wrapped in an Output)
*/
function ccJsonLoad(conditionJson) {
if ('hash' in conditionJson) {
var condition = new _fiveBellsCondition2.default.Condition();
condition.type = conditionJson.type_id;
condition.bitmask = conditionJson.bitmask;
condition.hash = new _buffer.Buffer(_bs2.default.decode(conditionJson.hash));
condition.maxFulfillmentLength = parseInt(conditionJson.max_fulfillment_length, 10);
return condition;
} else {
var fulfillment = void 0;
if (conditionJson.type_id === 2) {
fulfillment = new _fiveBellsCondition2.default.ThresholdSha256();
fulfillment.threshold = conditionJson.threshold;
conditionJson.subfulfillments.forEach(function (subfulfillment) {
subfulfillment = ccJsonLoad(subfulfillment);
if ('getConditionUri' in subfulfillment) fulfillment.addSubfulfillment(subfulfillment);else if ('serializeUri' in subfulfillment) fulfillment.addSubcondition(subfulfillment);
});
}
if (conditionJson.type_id === 0) {
fulfillment = new _fiveBellsCondition2.default.PreimageSha256();
fulfillment.preimage = new _buffer.Buffer(conditionJson.preimage);
}
if (conditionJson.type_id === 4) {
fulfillment = new _fiveBellsCondition2.default.Ed25519();
fulfillment.publicKey = new _buffer.Buffer(_bs2.default.decode(conditionJson.public_key));
if (conditionJson.signature) fulfillment.signature = new _buffer.Buffer(_bs2.default.decode(conditionJson.signature));
}
return fulfillment;
}
}
module.exports = exports['default'];

View File

@ -0,0 +1,75 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ccJsonify;
var _bs = require('bs58');
var _bs2 = _interopRequireDefault(_bs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @public
* Serializes a crypto-condition class (Condition or Fulfillment) into a BigchainDB-compatible JSON
* @param {cc.Fulfillment} fulfillment base58 encoded Ed25519 public key for the recipient of the Transaction
* @returns {object} Ed25519 Condition (that will need to wrapped in an Output)
*/
function ccJsonify(fulfillment) {
var conditionUri = void 0;
if ('getConditionUri' in fulfillment) conditionUri = fulfillment.getConditionUri();else if ('serializeUri' in fulfillment) conditionUri = fulfillment.serializeUri();
var jsonBody = {
'details': {},
'uri': conditionUri
};
if (fulfillment.getTypeId() === 0) {
jsonBody.details.type_id = 0;
jsonBody.details.bitmask = 3;
if ('preimage' in fulfillment) {
jsonBody.details.preimage = fulfillment.preimage.toString();
jsonBody.details.type = 'fulfillment';
}
}
if (fulfillment.getTypeId() === 2) return {
'details': {
'type_id': 2,
'type': 'fulfillment',
'bitmask': fulfillment.getBitmask(),
'threshold': fulfillment.threshold,
'subfulfillments': fulfillment.subconditions.map(function (subcondition) {
var subconditionJson = ccJsonify(subcondition.body);
subconditionJson.details.weight = 1;
return subconditionJson.details;
})
},
'uri': conditionUri
};
if (fulfillment.getTypeId() === 4) {
jsonBody.details.type_id = 4;
jsonBody.details.bitmask = 32;
if ('publicKey' in fulfillment) {
jsonBody.details.signature = null;
jsonBody.details.public_key = _bs2.default.encode(fulfillment.publicKey);
jsonBody.details.type = 'fulfillment';
}
}
if ('hash' in fulfillment) {
jsonBody.details.hash = _bs2.default.encode(fulfillment.hash);
jsonBody.details.max_fulfillment_length = fulfillment.maxFulfillmentLength;
jsonBody.details.type = 'condition';
}
return jsonBody;
}
module.exports = exports['default'];

View File

@ -1,6 +1,6 @@
{
"name": "js-bigchaindb-driver",
"version": "0.0.1",
"version": "0.0.2",
"description": "JavaScript driver for BigchainDB (node + browser)",
"homepage": "https://www.bigchaindb.com/",
"bugs": "https://github.com/bigchaindb/js-bigchaindb-driver/issues",

View File

@ -47,7 +47,7 @@ const config = {
output: {
filename: PRODUCTION ? 'bundle.min.js' : 'bundle.js',
library: 'js-bigchaindb-quickstart',
library: 'js-bigchaindb-driver',
libraryTarget: 'umd',
path: PATHS.BUNDLE,
},