@bitclave/base-client-js
Version:
Base JS library for BASE-platform
1,544 lines (1,285 loc) • 4.12 MB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("Base", [], factory);
else if(typeof exports === 'object')
exports["Base"] = factory();
else
root["Base"] = factory();
})(global, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/Base.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/aes/lib/aes.js":
/*!*************************************!*\
!*** ./node_modules/aes/lib/aes.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = AES;
//@param {Array} key The key as an array of 4, 6 or 8 words.
function AES (key) {
if (!this._tables[0][0][0]) this._precompute();
var tmp, encKey, decKey;
var sbox = this._tables[0][4];
var decTable = this._tables[1];
var keyLen = key.length;
var rcon = 1;
if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
throw new Error("invalid aes key size");
}
this._key = [encKey = key.slice(0), decKey = []];
// schedule encryption keys
for (var i = keyLen; i < 4 * keyLen + 28; i++) {
tmp = encKey[i-1];
// apply sbox
if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255]<< 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
// shift rows and add rcon
if (i % keyLen === 0) {
tmp = tmp << 8 ^ tmp >>> 24 ^ rcon<<24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
encKey[i] = encKey[i-keyLen] ^ tmp;
}
// schedule decryption keys
for (var j = 0; i; j++, i--) {
tmp = encKey[j&3 ? i : i - 4];
if (i<=4 || j<4) {
decKey[j] = tmp;
} else {
decKey[j] = decTable[0][sbox[tmp>>>24 ]] ^
decTable[1][sbox[tmp>>16 & 255]] ^
decTable[2][sbox[tmp>>8 & 255]] ^
decTable[3][sbox[tmp & 255]];
}
}
};
AES.prototype = {
/**
* Encrypt an array of 4 big-endian words.
* @param {Array} data The plaintext.
* @return {Array} The ciphertext.
*/
encrypt:function (data) { return this._crypt(data, 0); },
/**
* Decrypt an array of 4 big-endian words.
* @param {Array} data The ciphertext.
* @return {Array} The plaintext.
*/
decrypt:function (data) { return this._crypt(data, 1); },
/**
* The expanded S-box and inverse S-box tables. These will be computed
* on the client so that we don't have to send them down the wire.
*
* There are two tables, _tables[0] is for encryption and
* _tables[1] is for decryption.
*
* The first 4 sub-tables are the expanded S-box with MixColumns. The
* last (_tables[01][4]) is the S-box itself.
*
* @private
*/
_tables: [
[ new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256) ],
[ new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256) ]
],
//Expand the S-box tables.
_precompute: function () {
var encTable = this._tables[0], decTable = this._tables[1],
sbox = encTable[4], sboxInv = decTable[4],
i, x, xInv, d=new Uint8Array(256), th=new Uint8Array(256), x2, x4, x8, s, tEnc, tDec;
// Compute double and third tables
for (i = 0; i < 256; i++) {
th[( d[i] = i<<1 ^ (i>>7)*283 )^i]=i;
}
for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
// Compute sbox
s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
s = s >> 8 ^ s & 255 ^ 99;
sbox[x] = s;
sboxInv[s] = x;
// Compute MixColumns
x8 = d[x4 = d[x2 = d[x]]];
tDec = x8*0x1010101 ^ x4*0x10001 ^ x2*0x101 ^ x*0x1010100;
tEnc = d[s]*0x101 ^ s*0x1010100;
for (i = 0; i < 4; i++) {
encTable[i][x] = tEnc = tEnc<<24 ^ tEnc>>>8;
decTable[i][s] = tDec = tDec<<24 ^ tDec>>>8;
}
}
},
/**
* Encryption and decryption core.
* @param {Array} input Four words to be encrypted or decrypted.
* @param dir The direction, 0 for encrypt and 1 for decrypt.
* @return {Array} The four encrypted or decrypted words.
* @private
*/
_crypt:function (input, dir) {
if (input.length !== 4) {
throw new Error("invalid aes block size");
}
var key = this._key[dir],
// state variables a,b,c,d are loaded with pre-whitened data
a = input[0] ^ key[0],
b = input[dir ? 3 : 1] ^ key[1],
c = input[2] ^ key[2],
d = input[dir ? 1 : 3] ^ key[3],
a2, b2, c2,
nInnerRounds = key.length/4 - 2,
i,
kIndex = 4,
out = new Uint32Array(4),// <--- this is slower in Node.js, about the same in Chrome */
table = this._tables[dir],
// load up the tables
t0 = table[0],
t1 = table[1],
t2 = table[2],
t3 = table[3],
sbox = table[4];
// Inner rounds. Cribbed from OpenSSL.
for (i = 0; i < nInnerRounds; i++) {
a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex];
b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
d = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
kIndex += 4;
a=a2; b=b2; c=c2;
}
// Last round.
for (i = 0; i < 4; i++) {
out[dir ? 3&-i : i] =
sbox[a>>>24 ]<<24 ^
sbox[b>>16 & 255]<<16 ^
sbox[c>>8 & 255]<<8 ^
sbox[d & 255] ^
key[kIndex++];
a2=a; a=b; b=c; c=d; d=a2;
}
return out;
}
};
/***/ }),
/***/ "./node_modules/base-x/index.js":
/*!**************************************!*\
!*** ./node_modules/base-x/index.js ***!
\**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
const Buffer = __webpack_require__(/*! safe-buffer */ "./node_modules/safe-buffer/index.js").Buffer
module.exports = function base (ALPHABET) {
if (ALPHABET.length >= 255) throw new TypeError('Alphabet too long')
const BASE_MAP = new Uint8Array(256)
BASE_MAP.fill(255)
for (let i = 0; i < ALPHABET.length; i++) {
const x = ALPHABET.charAt(i)
const xc = x.charCodeAt(0)
if (BASE_MAP[xc] !== 255) throw new TypeError(x + ' is ambiguous')
BASE_MAP[xc] = i
}
const BASE = ALPHABET.length
const LEADER = ALPHABET.charAt(0)
const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up
function encode (source) {
if (!Buffer.isBuffer(source)) throw new TypeError('Expected Buffer')
if (source.length === 0) return ''
// Skip & count leading zeroes.
let zeroes = 0
let length = 0
let pbegin = 0
const pend = source.length
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++
zeroes++
}
// Allocate enough space in big-endian base58 representation.
const size = ((pend - pbegin) * iFACTOR + 1) >>> 0
const b58 = new Uint8Array(size)
// Process the bytes.
while (pbegin !== pend) {
let carry = source[pbegin]
// Apply "b58 = b58 * 256 + ch".
let i = 0
for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) {
carry += (256 * b58[it]) >>> 0
b58[it] = (carry % BASE) >>> 0
carry = (carry / BASE) >>> 0
}
if (carry !== 0) throw new Error('Non-zero carry')
length = i
pbegin++
}
// Skip leading zeroes in base58 result.
let it = size - length
while (it !== size && b58[it] === 0) {
it++
}
// Translate the result into a string.
let str = LEADER.repeat(zeroes)
for (; it < size; ++it) str += ALPHABET.charAt(b58[it])
return str
}
function decodeUnsafe (source) {
if (typeof source !== 'string') throw new TypeError('Expected String')
if (source.length === 0) return Buffer.alloc(0)
let psz = 0
// Skip leading spaces.
if (source[psz] === ' ') return
// Skip and count leading '1's.
let zeroes = 0
let length = 0
while (source[psz] === LEADER) {
zeroes++
psz++
}
// Allocate enough space in big-endian base256 representation.
const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
const b256 = new Uint8Array(size)
// Process the characters.
while (source[psz]) {
// Decode character
let carry = BASE_MAP[source.charCodeAt(psz)]
// Invalid character
if (carry === 255) return
let i = 0
for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) {
carry += (BASE * b256[it]) >>> 0
b256[it] = (carry % 256) >>> 0
carry = (carry / 256) >>> 0
}
if (carry !== 0) throw new Error('Non-zero carry')
length = i
psz++
}
// Skip trailing spaces.
if (source[psz] === ' ') return
// Skip leading zeroes in b256.
let it = size - length
while (it !== size && b256[it] === 0) {
it++
}
const vch = Buffer.allocUnsafe(zeroes + (size - it))
vch.fill(0x00, 0, zeroes)
let j = zeroes
while (it !== size) {
vch[j++] = b256[it++]
}
return vch
}
function decode (string) {
const buffer = decodeUnsafe(string)
if (buffer) return buffer
throw new Error('Non-base' + BASE + ' character')
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
}
}
/***/ }),
/***/ "./node_modules/bindings/bindings.js":
/*!*******************************************!*\
!*** ./node_modules/bindings/bindings.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(__filename) {/**
* Module dependencies.
*/
var fs = __webpack_require__(/*! fs */ "fs"),
path = __webpack_require__(/*! path */ "path"),
fileURLToPath = __webpack_require__(/*! file-uri-to-path */ "./node_modules/file-uri-to-path/index.js"),
join = path.join,
dirname = path.dirname,
exists =
(fs.accessSync &&
function(path) {
try {
fs.accessSync(path);
} catch (e) {
return false;
}
return true;
}) ||
fs.existsSync ||
path.existsSync,
defaults = {
arrow: process.env.NODE_BINDINGS_ARROW || ' → ',
compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled',
platform: process.platform,
arch: process.arch,
nodePreGyp:
'node-v' +
process.versions.modules +
'-' +
process.platform +
'-' +
process.arch,
version: process.versions.node,
bindings: 'bindings.node',
try: [
// node-gyp's linked version in the "build" dir
['module_root', 'build', 'bindings'],
// node-waf and gyp_addon (a.k.a node-gyp)
['module_root', 'build', 'Debug', 'bindings'],
['module_root', 'build', 'Release', 'bindings'],
// Debug files, for development (legacy behavior, remove for node v0.9)
['module_root', 'out', 'Debug', 'bindings'],
['module_root', 'Debug', 'bindings'],
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
['module_root', 'out', 'Release', 'bindings'],
['module_root', 'Release', 'bindings'],
// Legacy from node-waf, node <= 0.4.x
['module_root', 'build', 'default', 'bindings'],
// Production "Release" buildtype binary (meh...)
['module_root', 'compiled', 'version', 'platform', 'arch', 'bindings'],
// node-qbs builds
['module_root', 'addon-build', 'release', 'install-root', 'bindings'],
['module_root', 'addon-build', 'debug', 'install-root', 'bindings'],
['module_root', 'addon-build', 'default', 'install-root', 'bindings'],
// node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
['module_root', 'lib', 'binding', 'nodePreGyp', 'bindings']
]
};
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
function bindings(opts) {
// Argument surgery
if (typeof opts == 'string') {
opts = { bindings: opts };
} else if (!opts) {
opts = {};
}
// maps `defaults` onto `opts` object
Object.keys(defaults).map(function(i) {
if (!(i in opts)) opts[i] = defaults[i];
});
// Get the module root
if (!opts.module_root) {
opts.module_root = exports.getRoot(exports.getFileName());
}
// Ensure the given bindings name ends with .node
if (path.extname(opts.bindings) != '.node') {
opts.bindings += '.node';
}
// https://github.com/webpack/webpack/issues/4175#issuecomment-342931035
var requireFunc =
true
? require
: undefined;
var tries = [],
i = 0,
l = opts.try.length,
n,
b,
err;
for (; i < l; i++) {
n = join.apply(
null,
opts.try[i].map(function(p) {
return opts[p] || p;
})
);
tries.push(n);
try {
b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
if (!opts.path) {
b.path = n;
}
return b;
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND' &&
e.code !== 'QUALIFIED_PATH_RESOLUTION_FAILED' &&
!/not find/i.test(e.message)) {
throw e;
}
}
}
err = new Error(
'Could not locate the bindings file. Tried:\n' +
tries
.map(function(a) {
return opts.arrow + a;
})
.join('\n')
);
err.tries = tries;
throw err;
}
module.exports = exports = bindings;
/**
* Gets the filename of the JavaScript file that invokes this function.
* Used to help find the root directory of a module.
* Optionally accepts an filename argument to skip when searching for the invoking filename
*/
exports.getFileName = function getFileName(calling_file) {
var origPST = Error.prepareStackTrace,
origSTL = Error.stackTraceLimit,
dummy = {},
fileName;
Error.stackTraceLimit = 10;
Error.prepareStackTrace = function(e, st) {
for (var i = 0, l = st.length; i < l; i++) {
fileName = st[i].getFileName();
if (fileName !== __filename) {
if (calling_file) {
if (fileName !== calling_file) {
return;
}
} else {
return;
}
}
}
};
// run the 'prepareStackTrace' function above
Error.captureStackTrace(dummy);
dummy.stack;
// cleanup
Error.prepareStackTrace = origPST;
Error.stackTraceLimit = origSTL;
// handle filename that starts with "file://"
var fileSchema = 'file://';
if (fileName.indexOf(fileSchema) === 0) {
fileName = fileURLToPath(fileName);
}
return fileName;
};
/**
* Gets the root directory of a module, given an arbitrary filename
* somewhere in the module tree. The "root directory" is the directory
* containing the `package.json` file.
*
* In: /home/nate/node-native-module/lib/index.js
* Out: /home/nate/node-native-module
*/
exports.getRoot = function getRoot(file) {
var dir = dirname(file),
prev;
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd();
}
if (
exists(join(dir, 'package.json')) ||
exists(join(dir, 'node_modules'))
) {
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir;
}
if (prev === dir) {
// Got to the top
throw new Error(
'Could not find module root given file: "' +
file +
'". Do you have a `package.json` file? '
);
}
// Try the parent dir next
prev = dir;
dir = join(dir, '..');
}
};
/* WEBPACK VAR INJECTION */}.call(this, "/index.js"))
/***/ }),
/***/ "./node_modules/bip66/index.js":
/*!*************************************!*\
!*** ./node_modules/bip66/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
// NOTE: SIGHASH byte ignored AND restricted, truncate before use
var Buffer = __webpack_require__(/*! safe-buffer */ "./node_modules/safe-buffer/index.js").Buffer
function check (buffer) {
if (buffer.length < 8) return false
if (buffer.length > 72) return false
if (buffer[0] !== 0x30) return false
if (buffer[1] !== buffer.length - 2) return false
if (buffer[2] !== 0x02) return false
var lenR = buffer[3]
if (lenR === 0) return false
if (5 + lenR >= buffer.length) return false
if (buffer[4 + lenR] !== 0x02) return false
var lenS = buffer[5 + lenR]
if (lenS === 0) return false
if ((6 + lenR + lenS) !== buffer.length) return false
if (buffer[4] & 0x80) return false
if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false
if (buffer[lenR + 6] & 0x80) return false
if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false
return true
}
function decode (buffer) {
if (buffer.length < 8) throw new Error('DER sequence length is too short')
if (buffer.length > 72) throw new Error('DER sequence length is too long')
if (buffer[0] !== 0x30) throw new Error('Expected DER sequence')
if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid')
if (buffer[2] !== 0x02) throw new Error('Expected DER integer')
var lenR = buffer[3]
if (lenR === 0) throw new Error('R length is zero')
if (5 + lenR >= buffer.length) throw new Error('R length is too long')
if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)')
var lenS = buffer[5 + lenR]
if (lenS === 0) throw new Error('S length is zero')
if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid')
if (buffer[4] & 0x80) throw new Error('R value is negative')
if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded')
if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative')
if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded')
// non-BIP66 - extract R, S values
return {
r: buffer.slice(4, 4 + lenR),
s: buffer.slice(6 + lenR)
}
}
/*
* Expects r and s to be positive DER integers.
*
* The DER format uses the most significant bit as a sign bit (& 0x80).
* If the significant bit is set AND the integer is positive, a 0x00 is prepended.
*
* Examples:
*
* 0 => 0x00
* 1 => 0x01
* -1 => 0xff
* 127 => 0x7f
* -127 => 0x81
* 128 => 0x0080
* -128 => 0x80
* 255 => 0x00ff
* -255 => 0xff01
* 16300 => 0x3fac
* -16300 => 0xc054
* 62300 => 0x00f35c
* -62300 => 0xff0ca4
*/
function encode (r, s) {
var lenR = r.length
var lenS = s.length
if (lenR === 0) throw new Error('R length is zero')
if (lenS === 0) throw new Error('S length is zero')
if (lenR > 33) throw new Error('R length is too long')
if (lenS > 33) throw new Error('S length is too long')
if (r[0] & 0x80) throw new Error('R value is negative')
if (s[0] & 0x80) throw new Error('S value is negative')
if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
var signature = Buffer.allocUnsafe(6 + lenR + lenS)
// 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
signature[0] = 0x30
signature[1] = signature.length - 2
signature[2] = 0x02
signature[3] = r.length
r.copy(signature, 4)
signature[4 + lenR] = 0x02
signature[5 + lenR] = s.length
s.copy(signature, 6 + lenR)
return signature
}
module.exports = {
check: check,
decode: decode,
encode: encode
}
/***/ }),
/***/ "./node_modules/bitcore-ecies/index.js":
/*!*********************************************!*\
!*** ./node_modules/bitcore-ecies/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./lib/ecies */ "./node_modules/bitcore-ecies/lib/ecies.js");
/***/ }),
/***/ "./node_modules/bitcore-ecies/lib/aes.js":
/*!***********************************************!*\
!*** ./node_modules/bitcore-ecies/lib/aes.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bitcore = __webpack_require__(/*! bitcore-lib */ "./node_modules/bitcore-lib/index.js");
var $ = bitcore.util.preconditions;
var aes = __webpack_require__(/*! aes */ "./node_modules/aes/lib/aes.js");
var AES = function AES() {};
AES.encrypt = function(messagebuf, keybuf) {
var key = AES.buf2words(keybuf);
var message = AES.buf2words(messagebuf);
var a = new aes(key);
var enc = a.encrypt(message);
var encbuf = AES.words2buf(enc);
return encbuf;
};
AES.decrypt = function(encbuf, keybuf) {
var enc = AES.buf2words(encbuf);
var key = AES.buf2words(keybuf);
var a = new aes(key);
var message = a.decrypt(enc);
var messagebuf = AES.words2buf(message);
return messagebuf;
};
AES.buf2words = function(buf) {
$.checkArgument(buf);
$.checkArgument(buf.length % 4 === 0, 'buf length must be a multiple of 4');
var words = [];
for (var i = 0; i < buf.length / 4; i++) {
words.push(buf.readUInt32BE(i * 4));
}
return words;
};
AES.words2buf = function(words) {
var buf = new Buffer(words.length * 4);
for (var i = 0; i < words.length; i++) {
buf.writeUInt32BE(words[i], i * 4);
}
return buf;
};
module.exports = AES;
/***/ }),
/***/ "./node_modules/bitcore-ecies/lib/aescbc.js":
/*!**************************************************!*\
!*** ./node_modules/bitcore-ecies/lib/aescbc.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bitcore = __webpack_require__(/*! bitcore-lib */ "./node_modules/bitcore-lib/index.js");
var $ = bitcore.util.preconditions;
var AES = __webpack_require__(/*! ./aes */ "./node_modules/bitcore-ecies/lib/aes.js");
var CBC = __webpack_require__(/*! ./cbc */ "./node_modules/bitcore-ecies/lib/cbc.js");
var Random = bitcore.crypto.Random;
var Hash = bitcore.crypto.Hash;
// Symmetric encryption with AES and CBC convenience class
var AESCBC = function AESCBC() {};
AESCBC.encrypt = function(messagebuf, passwordstr) {
$.checkArgument(messagebuf);
$.checkArgument(passwordstr);
var cipherkeybuf = Hash.sha256(new Buffer(passwordstr));
return AESCBC.encryptCipherkey(messagebuf, cipherkeybuf);
};
AESCBC.decrypt = function(encbuf, passwordstr) {
$.checkArgument(encbuf);
$.checkArgument(passwordstr);
var cipherkeybuf = Hash.sha256(new Buffer(passwordstr));
return AESCBC.decryptCipherkey(encbuf, cipherkeybuf);
};
AESCBC.encryptCipherkey = function(messagebuf, cipherkeybuf, ivbuf) {
$.checkArgument(messagebuf);
$.checkArgument(cipherkeybuf);
$.checkArgument(ivbuf);
ivbuf = ivbuf || Random.getRandomBuffer(128 / 8);
var ctbuf = CBC.encrypt(messagebuf, ivbuf, AES, cipherkeybuf);
var encbuf = Buffer.concat([ivbuf, ctbuf]);
return encbuf;
};
AESCBC.decryptCipherkey = function(encbuf, cipherkeybuf) {
$.checkArgument(encbuf);
$.checkArgument(cipherkeybuf);
var ivbuf = encbuf.slice(0, 128 / 8);
var ctbuf = encbuf.slice(128 / 8);
var messagebuf = CBC.decrypt(ctbuf, ivbuf, AES, cipherkeybuf);
return messagebuf;
};
module.exports = AESCBC;
/***/ }),
/***/ "./node_modules/bitcore-ecies/lib/cbc.js":
/*!***********************************************!*\
!*** ./node_modules/bitcore-ecies/lib/cbc.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var errors = __webpack_require__(/*! ./errors */ "./node_modules/bitcore-ecies/lib/errors.js");
var bitcore = __webpack_require__(/*! bitcore-lib */ "./node_modules/bitcore-lib/index.js");
var $ = bitcore.util.preconditions;
// Cipher Block Chaining
// http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29
var CBC = function CBC(blockcipher, cipherkeybuf, ivbuf) {
if (!(this instanceof CBC)) {
return new CBC(blockcipher, cipherkeybuf, ivbuf);
}
this.blockcipher = blockcipher;
this.cipherkeybuf = cipherkeybuf;
this.ivbuf = ivbuf;
};
CBC.buf2blockbufs = function(buf, blocksize) {
var bytesize = blocksize / 8;
var blockbufs = [];
for (var i = 0; i <= buf.length / bytesize; i++) {
var blockbuf = buf.slice(i * bytesize, i * bytesize + bytesize);
if (blockbuf.length < blocksize) {
blockbuf = CBC.pkcs7pad(blockbuf, blocksize);
}
blockbufs.push(blockbuf);
}
return blockbufs;
};
CBC.blockbufs2buf = function(blockbufs) {
var last = blockbufs[blockbufs.length - 1];
last = CBC.pkcs7unpad(last);
blockbufs[blockbufs.length - 1] = last;
var buf = Buffer.concat(blockbufs);
return buf;
};
CBC.encrypt = function(messagebuf, ivbuf, blockcipher, cipherkeybuf) {
var blocksize = ivbuf.length * 8;
var blockbufs = CBC.buf2blockbufs(messagebuf, blocksize);
var encbufs = CBC.encryptblocks(blockbufs, ivbuf, blockcipher, cipherkeybuf);
var encbuf = Buffer.concat(encbufs);
return encbuf;
};
CBC.decrypt = function(encbuf, ivbuf, blockcipher, cipherkeybuf) {
var blocksize = ivbuf.length * 8;
var bytesize = ivbuf.length;
var encbufs = [];
for (var i = 0; i < encbuf.length / bytesize; i++) {
encbufs.push(encbuf.slice(i * bytesize, i * bytesize + bytesize));
}
var blockbufs = CBC.decryptblocks(encbufs, ivbuf, blockcipher, cipherkeybuf);
var buf = CBC.blockbufs2buf(blockbufs, blocksize);
return buf;
};
CBC.encryptblock = function(blockbuf, ivbuf, blockcipher, cipherkeybuf) {
var xorbuf = CBC.xorbufs(blockbuf, ivbuf);
var encbuf = blockcipher.encrypt(xorbuf, cipherkeybuf);
return encbuf;
};
CBC.decryptblock = function(encbuf, ivbuf, blockcipher, cipherkeybuf) {
var xorbuf = blockcipher.decrypt(encbuf, cipherkeybuf);
var blockbuf = CBC.xorbufs(xorbuf, ivbuf);
return blockbuf;
};
CBC.encryptblocks = function(blockbufs, ivbuf, blockcipher, cipherkeybuf) {
var encbufs = [];
for (var i = 0; i < blockbufs.length; i++) {
var blockbuf = blockbufs[i];
var encbuf = CBC.encryptblock(blockbuf, ivbuf, blockcipher, cipherkeybuf);
encbufs.push(encbuf);
ivbuf = encbuf;
}
return encbufs;
};
CBC.decryptblocks = function(encbufs, ivbuf, blockcipher, cipherkeybuf) {
var blockbufs = [];
for (var i = 0; i < encbufs.length; i++) {
var encbuf = encbufs[i];
var blockbuf = CBC.decryptblock(encbuf, ivbuf, blockcipher, cipherkeybuf);
blockbufs.push(blockbuf);
ivbuf = encbuf;
}
return blockbufs;
};
CBC.pkcs7pad = function(buf, blocksize) {
var bytesize = blocksize / 8;
var padbytesize = bytesize - buf.length;
var pad = new Buffer(padbytesize);
pad.fill(padbytesize);
var paddedbuf = Buffer.concat([buf, pad]);
return paddedbuf;
};
CBC.pkcs7unpad = function(paddedbuf) {
var padlength = paddedbuf[paddedbuf.length - 1];
var padbuf = paddedbuf.slice(paddedbuf.length - padlength, paddedbuf.length);
var padbuf2 = new Buffer(padlength);
padbuf2.fill(padlength);
if (padbuf.toString('hex') !== padbuf2.toString('hex')) {
throw new errors.InvalidPadding(padbuf.toString());
}
return paddedbuf.slice(0, paddedbuf.length - padlength);
};
CBC.xorbufs = function(buf1, buf2) {
$.checkArgument(buf1.length === buf2.length, 'bufs must have the same length');
var buf = new Buffer(buf1.length);
for (var i = 0; i < buf1.length; i++) {
buf[i] = buf1[i] ^ buf2[i];
}
return buf;
};
module.exports = CBC;
/***/ }),
/***/ "./node_modules/bitcore-ecies/lib/ecies.js":
/*!*************************************************!*\
!*** ./node_modules/bitcore-ecies/lib/ecies.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bitcore = __webpack_require__(/*! bitcore-lib */ "./node_modules/bitcore-lib/index.js");
var PublicKey = bitcore.PublicKey;
var Hash = bitcore.crypto.Hash;
var Random = bitcore.crypto.Random;
var $ = bitcore.util.preconditions;
var AESCBC = __webpack_require__(/*! ./aescbc */ "./node_modules/bitcore-ecies/lib/aescbc.js");
// http://en.wikipedia.org/wiki/Integrated_Encryption_Scheme
var ECIES = function ECIES(opts) {
if (!(this instanceof ECIES)) {
return new ECIES();
}
this.opts = opts || {};
};
ECIES.prototype.privateKey = function(privateKey) {
$.checkArgument(privateKey, 'no private key provided');
this._privateKey = privateKey || null;
return this;
};
ECIES.prototype.publicKey = function(publicKey) {
$.checkArgument(publicKey, 'no public key provided');
this._publicKey = publicKey || null;
return this;
};
var cachedProperty = function(name, getter) {
var cachedName = '_' + name;
Object.defineProperty(ECIES.prototype, name, {
configurable: false,
enumerable: true,
get: function() {
var value = this[cachedName];
if (!value) {
value = this[cachedName] = getter.apply(this);
}
return value;
}
});
};
cachedProperty('Rbuf', function() {
return this._privateKey.publicKey.toDER(true);
});
cachedProperty('kEkM', function() {
var r = this._privateKey.bn;
var KB = this._publicKey.point;
var P = KB.mul(r);
var S = P.getX();
var Sbuf = S.toBuffer({size: 32});
return Hash.sha512(Sbuf);
});
cachedProperty('kE', function() {
return this.kEkM.slice(0, 32);
});
cachedProperty('kM', function() {
return this.kEkM.slice(32,64);
});
// Encrypts the message (String or Buffer).
// Optional `ivbuf` contains 16-byte Buffer to be used in AES-CBC.
// By default, `ivbuf` is computed deterministically from message and private key using HMAC-SHA256.
// Deterministic IV enables end-to-end test vectors for alternative implementations.
// Note that identical messages have identical ciphertexts. If your protocol does not include some
// kind of a sequence identifier inside the message *and* it is important to not allow attacker to learn
// that message is repeated, then you should use custom IV.
// For random IV, pass `Random.getRandomBuffer(16)` for the second argument.
ECIES.prototype.encrypt = function(message, ivbuf) {
if (!Buffer.isBuffer(message)) message = new Buffer(message);
if (ivbuf === undefined) {
ivbuf = Hash.sha256hmac(message, this._privateKey.toBuffer()).slice(0,16);
}
var c = AESCBC.encryptCipherkey(message, this.kE, ivbuf);
var d = Hash.sha256hmac(c, this.kM);
if(this.opts.shortTag) d = d.slice(0,4);
if(this.opts.noKey) {
var encbuf = Buffer.concat([c, d]);
} else {
var encbuf = Buffer.concat([this.Rbuf, c, d]);
}
return encbuf;
};
ECIES.prototype.decrypt = function(encbuf) {
$.checkArgument(encbuf);
var offset = 0;
var tagLength = 32;
if(this.opts.shortTag) {
tagLength = 4;
}
if(!this.opts.noKey) {
var pub;
switch(encbuf[0]) {
case 4:
pub = encbuf.slice(0, 65);
break;
case 3:
case 2:
pub = encbuf.slice(0, 33);
break;
default:
throw new Error('Invalid type: ' + encbuf[0]);
}
this._publicKey = PublicKey.fromDER(pub);
offset += pub.length;
}
var c = encbuf.slice(offset, encbuf.length - tagLength);
var d = encbuf.slice(encbuf.length - tagLength, encbuf.length);
var d2 = Hash.sha256hmac(c, this.kM);
if(this.opts.shortTag) d2 = d2.slice(0,4);
var equal = true;
for (var i = 0; i < d.length; i++) {
equal &= (d[i] === d2[i]);
}
if (!equal) {
throw new Error('Invalid checksum');
}
return AESCBC.decryptCipherkey(c, this.kE);
};
module.exports = ECIES;
/***/ }),
/***/ "./node_modules/bitcore-ecies/lib/errors.js":
/*!**************************************************!*\
!*** ./node_modules/bitcore-ecies/lib/errors.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var spec = {
name: 'ECIES',
message: 'Internal Error on bitcore-ecies Module {0}',
errors: [{
name: 'InvalidPadding',
message: 'Invalid padding: {0}'
}]
};
module.exports = __webpack_require__(/*! bitcore-lib */ "./node_modules/bitcore-lib/index.js").errors.extend(spec);
/***/ }),
/***/ "./node_modules/bitcore-lib/index.js":
/*!*******************************************!*\
!*** ./node_modules/bitcore-lib/index.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bitcore = module.exports;
// module information
bitcore.version = 'v' + __webpack_require__(/*! ./package.json */ "./node_modules/bitcore-lib/package.json").version;
bitcore.versionGuard = function(version) {
if (version !== undefined) {
var message = 'More than one instance of bitcore-lib found. ' +
'Please make sure to require bitcore-lib and check that submodules do' +
' not also include their own bitcore-lib dependency.';
throw new Error(message);
}
};
bitcore.versionGuard(global._bitcore);
global._bitcore = bitcore.version;
// crypto
bitcore.crypto = {};
bitcore.crypto.BN = __webpack_require__(/*! ./lib/crypto/bn */ "./node_modules/bitcore-lib/lib/crypto/bn.js");
bitcore.crypto.ECDSA = __webpack_require__(/*! ./lib/crypto/ecdsa */ "./node_modules/bitcore-lib/lib/crypto/ecdsa.js");
bitcore.crypto.Hash = __webpack_require__(/*! ./lib/crypto/hash */ "./node_modules/bitcore-lib/lib/crypto/hash.js");
bitcore.crypto.Random = __webpack_require__(/*! ./lib/crypto/random */ "./node_modules/bitcore-lib/lib/crypto/random.js");
bitcore.crypto.Point = __webpack_require__(/*! ./lib/crypto/point */ "./node_modules/bitcore-lib/lib/crypto/point.js");
bitcore.crypto.Signature = __webpack_require__(/*! ./lib/crypto/signature */ "./node_modules/bitcore-lib/lib/crypto/signature.js");
// encoding
bitcore.encoding = {};
bitcore.encoding.Base58 = __webpack_require__(/*! ./lib/encoding/base58 */ "./node_modules/bitcore-lib/lib/encoding/base58.js");
bitcore.encoding.Base58Check = __webpack_require__(/*! ./lib/encoding/base58check */ "./node_modules/bitcore-lib/lib/encoding/base58check.js");
bitcore.encoding.BufferReader = __webpack_require__(/*! ./lib/encoding/bufferreader */ "./node_modules/bitcore-lib/lib/encoding/bufferreader.js");
bitcore.encoding.BufferWriter = __webpack_require__(/*! ./lib/encoding/bufferwriter */ "./node_modules/bitcore-lib/lib/encoding/bufferwriter.js");
bitcore.encoding.Varint = __webpack_require__(/*! ./lib/encoding/varint */ "./node_modules/bitcore-lib/lib/encoding/varint.js");
// utilities
bitcore.util = {};
bitcore.util.buffer = __webpack_require__(/*! ./lib/util/buffer */ "./node_modules/bitcore-lib/lib/util/buffer.js");
bitcore.util.js = __webpack_require__(/*! ./lib/util/js */ "./node_modules/bitcore-lib/lib/util/js.js");
bitcore.util.preconditions = __webpack_require__(/*! ./lib/util/preconditions */ "./node_modules/bitcore-lib/lib/util/preconditions.js");
// errors thrown by the library
bitcore.errors = __webpack_require__(/*! ./lib/errors */ "./node_modules/bitcore-lib/lib/errors/index.js");
// main bitcoin library
bitcore.Address = __webpack_require__(/*! ./lib/address */ "./node_modules/bitcore-lib/lib/address.js");
bitcore.Block = __webpack_require__(/*! ./lib/block */ "./node_modules/bitcore-lib/lib/block/index.js");
bitcore.MerkleBlock = __webpack_require__(/*! ./lib/block/merkleblock */ "./node_modules/bitcore-lib/lib/block/merkleblock.js");
bitcore.BlockHeader = __webpack_require__(/*! ./lib/block/blockheader */ "./node_modules/bitcore-lib/lib/block/blockheader.js");
bitcore.HDPrivateKey = __webpack_require__(/*! ./lib/hdprivatekey.js */ "./node_modules/bitcore-lib/lib/hdprivatekey.js");
bitcore.HDPublicKey = __webpack_require__(/*! ./lib/hdpublickey.js */ "./node_modules/bitcore-lib/lib/hdpublickey.js");
bitcore.Message = __webpack_require__(/*! ./lib/message */ "./node_modules/bitcore-lib/lib/message.js");
bitcore.Networks = __webpack_require__(/*! ./lib/networks */ "./node_modules/bitcore-lib/lib/networks.js");
bitcore.Opcode = __webpack_require__(/*! ./lib/opcode */ "./node_modules/bitcore-lib/lib/opcode.js");
bitcore.PrivateKey = __webpack_require__(/*! ./lib/privatekey */ "./node_modules/bitcore-lib/lib/privatekey.js");
bitcore.PublicKey = __webpack_require__(/*! ./lib/publickey */ "./node_modules/bitcore-lib/lib/publickey.js");
bitcore.Script = __webpack_require__(/*! ./lib/script */ "./node_modules/bitcore-lib/lib/script/index.js");
bitcore.Transaction = __webpack_require__(/*! ./lib/transaction */ "./node_modules/bitcore-lib/lib/transaction/index.js");
bitcore.URI = __webpack_require__(/*! ./lib/uri */ "./node_modules/bitcore-lib/lib/uri.js");
bitcore.Unit = __webpack_require__(/*! ./lib/unit */ "./node_modules/bitcore-lib/lib/unit.js");
// dependencies, subject to change
bitcore.deps = {};
bitcore.deps.bnjs = __webpack_require__(/*! bn.js */ "./node_modules/bn.js/lib/bn.js");
bitcore.deps.bs58 = __webpack_require__(/*! bs58 */ "./node_modules/bs58/index.js");
bitcore.deps.Buffer = Buffer;
bitcore.deps.elliptic = __webpack_require__(/*! elliptic */ "./node_modules/elliptic/lib/elliptic.js");
bitcore.deps._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
// Internal usage, exposed for testing/advanced tweaking
bitcore.Transaction.sighash = __webpack_require__(/*! ./lib/transaction/sighash */ "./node_modules/bitcore-lib/lib/transaction/sighash.js");
/***/ }),
/***/ "./node_modules/bitcore-lib/lib/address.js":
/*!*************************************************!*\
!*** ./node_modules/bitcore-lib/lib/address.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
var $ = __webpack_require__(/*! ./util/preconditions */ "./node_modules/bitcore-lib/lib/util/preconditions.js");
var errors = __webpack_require__(/*! ./errors */ "./node_modules/bitcore-lib/lib/errors/index.js");
var Base58Check = __webpack_require__(/*! ./encoding/base58check */ "./node_modules/bitcore-lib/lib/encoding/base58check.js");
var Networks = __webpack_require__(/*! ./networks */ "./node_modules/bitcore-lib/lib/networks.js");
var Hash = __webpack_require__(/*! ./crypto/hash */ "./node_modules/bitcore-lib/lib/crypto/hash.js");
var JSUtil = __webpack_require__(/*! ./util/js */ "./node_modules/bitcore-lib/lib/util/js.js");
var PublicKey = __webpack_require__(/*! ./publickey */ "./node_modules/bitcore-lib/lib/publickey.js");
/**
* Instantiate an address from an address String or Buffer, a public key or script hash Buffer,
* or an instance of {@link PublicKey} or {@link Script}.
*
* This is an immutable class, and if the first parameter provided to this constructor is an
* `Address` instance, the same argument will be returned.
*
* An address has two key properties: `network` and `type`. The type is either
* `Address.PayToPublicKeyHash` (value is the `'pubkeyhash'` string)
* or `Address.PayToScriptHash` (the string `'scripthash'`). The network is an instance of {@link Network}.
* You can quickly check whether an address is of a given kind by using the methods
* `isPayToPublicKeyHash` and `isPayToScriptHash`
*
* @example
* ```javascript
* // validate that an input field is valid
* var error = Address.getValidationError(input, 'testnet');
* if (!error) {
* var address = Address(input, 'testnet');
* } else {
* // invalid network or checksum (typo?)
* var message = error.messsage;
* }
*
* // get an address from a public key
* var address = Address(publicKey, 'testnet').toString();
* ```
*
* @param {*} data - The encoded data in various formats
* @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
* @param {string=} type - The type of address: 'script' or 'pubkey'
* @returns {Address} A new valid and frozen instance of an Address
* @constructor
*/
function Address(data, network, type) {
/* jshint maxcomplexity: 12 */
/* jshint maxstatements: 20 */
if (!(this instanceof Address)) {
return new Address(data, network, type);
}
if (_.isArray(data) && _.isNumber(network)) {
return Address.createMultisig(data, network, type);
}
if (data instanceof Address) {
// Immutable instance
return data;
}
$.checkArgument(data, 'First argument is required, please include address data.', 'guide/address.html');
if (network && !Networks.get(network)) {
throw new TypeError('Second argument must be "livenet" or "testnet".');
}
if (type && (type !== Address.PayToPublicKeyHash && type !== Address.PayToScriptHash)) {
throw new TypeError('Third argument must be "pubkeyhash" or "scripthash".');
}
var info = this._classifyArguments(data, network, type);
// set defaults if not set
info.network = info.network || Networks.get(network) || Networks.defaultNetwork;
info.type = info.type || type || Address.PayToPublicKeyHash;
JSUtil.defineImmutable(this, {
hashBuffer: info.hashBuffer,
network: info.network,
type: info.type
});
return this;
}
/**
* Internal function used to split different kinds of arguments of the constructor
* @param {*} data - The encoded data in various formats
* @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
* @param {string=} type - The type of address: 'script' or 'pubkey'
* @returns {Object} An "info" object with "type", "network", and "hashBuffer"
*/
Address.prototype._classifyArguments = function(data, network, type) {
/* jshint maxcomplexity: 10 */
// transform and validate input data
if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 20) {
return Address._transformHash(data);
} else if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 21) {
return Address._transformBuffer(data, network, type);
} else if (data instanceof PublicKey) {
return Address._transformPublicKey(data);
} else if (data instanceof Script) {
return Address._transformScript(data, network);
} else if (typeof(data) === 'string') {
return Address._transformString(data, network, type);
} else if (_.isObject(data)) {
return Address._transformObject(data);
} else {
throw new TypeError('First argument is an unrecognized data format.');
}
};
/** @static */
Address.PayToPublicKeyHash = 'pubkeyhash';
/** @static */
Address.PayToScriptHash = 'scripthash';
/**
* @param {Buffer} hash - An instance of a hash Buffer
* @returns {Object} An object with keys: hashBuffer
* @private
*/
Address._transformHash = function(hash) {
var info = {};
if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) {
throw new TypeError('Address supplied is not a buffer.');
}
if (hash.length !== 20) {
throw new TypeError('Address hashbuffers must be exactly 20 bytes.');
}
info.hashBuffer = hash;
return info;
};
/**
* Deserializes an address serialized through `Address#toObject()`
* @param {Object} data
* @param {string} data.hash - the hash that this address encodes
* @param {string} data.type - either 'pubkeyhash' or 'scripthash'
* @param {Network=} data.network - the name of the network associated
* @return {Address}
*/
Address._transformObject = function(data) {
$.checkArgument(data.hash || data.hashBuffer, 'Must provide a `hash` or `hashBuffer` property');
$.checkArgument(data.type, 'Must provide a `type` property');
return {
hashBuffer: data.hash ? Buffer.from(data.hash, 'hex') : data.hashBuffer,
network: Networks.get(data.network) || Networks.defaultNetwork,
type: data.type
};
};
/**
* Internal function to discover the network and type based on the first data byte
*
* @param {Buffer} buffer - An instance of a hex encoded address Buffer
* @returns {Object} An object with keys: network and type
* @private
*/
Address._classifyFromVersion = function(buffer) {
var version = {};
var pubkeyhashNetwork = Networks.get(buffer[0], 'pubkeyhash');
var scripthashNetwork = Networks.get(buffer[0], 'scripthash');
if (pubkeyhashNetwork) {
version.network = pubkeyhashNetwork;
version.type = Address.PayToPublicKeyHash;
} else if (scripthashNetwork) {
version.network = scripthashNetwork;
version.type = Address.PayToScriptHash;
}
return version;
};
/**
* Internal function to transform a bitcoin address buffer
*
* @param {Buffer} buffer - An instance of a hex encoded address Buffer
* @param {string=} network - The network: 'livenet' or 'testnet'
* @param {string=} type - The type: 'pubkeyhash' or 'scripthash'
* @returns {Object} An object with keys: hashBuffer, network and type
* @private
*/
Address._transformBuffer = function(buffer, network, type) {
/* jshint maxcomplexity: 9 */
var info = {};
if (!(buffer instanceof Buffer) && !(buffer instanceof Uint8Array)) {
throw new TypeError('Address supplied is not a buffer.');
}
if (buff