https://github.com/bitcoinjs/bitcoinjs-lib/issues/14
516147
function numToBytes(num, bytes) {
  if (bytes == 0) return [];else return [num % 256].concat(numToBytes(Math.floor(num / 256), bytes - 1));
}
1371493
function ( n, buffer, bytes ) {
                var s = ( n % k ) * slen
                    // how many bytes to read/consume from the input buffer [1 to 4]
                    , rbytes = bytes >>> 0 ? abs( bytes ) % 5 : ibytes
                    , blen = buffer.length - rbytes
                    , bruint = null
                    , sum = 0
                    , b = 0
                    ;
                /*
                 * NOTE: js is not capable to handle integers larger than ~2^53,
                 * when the sum exceeds this limit, we expect to get get biased
                 * results, or in other words, more collisions. It will happens
                 * when we are using large primes as range, or with long buffer
                 * in input. If sum === sum + 1, we could break the for cycle.
                 */
                if ( rbytes === 1 ) {
                    // use [] notation when reading input, 1 byte at the time.
                    if ( ibytes === 1 ) {
                        // read input and seed 1 byte at the time
                        for ( ; b <= blen && s <= rlen; ++b, ++s )
                            sum += buffer[ b ] * result[ s ];
                        return sum % prange;
                    }
                    for ( ; b <= blen && s <= rlen; ++b, s += ibytes )
                        sum += buffer[ b ] * result[ ruint ]( s );
                    return sum % prange;
                }
                // build string for read method (16, 24 or 32 bits unsigned integers)
                bruint =  bruint = 'readUInt' + ( rbytes << 3 ) + 'BE';
                for ( ; b <= blen && s <= rlen; b += rbytes, s += ibytes ) {
                    sum += buffer[ bruint ]( b ) * result[ ruint ]( s );
                    sum %= prange;
                }
                return sum;
            }
1151447
async function () {
    const oThis = this
    ;

    // validations
    if (!basicHelper.isNonZeroWeiValid(oThis.amountToStakeInWeis)) {
      logger.error('Invalid amount');
      process.exit(1);
    }

    // Format to big number
    oThis.amountToStakeInWeis = basicHelper.convertToBigNumber(oThis.amountToStakeInWeis);

    const amountToStakeForBT = ((oThis.amountToStakeInWeis.mul(0.9)).minus(oThis.amountToStakeInWeis.mul(0.9).modulo(1)))
      , amountToStakeForSTP = oThis.amountToStakeInWeis.minus(amountToStakeForBT)
      , stPrimeUuid = coreConstants.OST_OPENSTUTILITY_ST_PRIME_UUID
    ;

    // validations
    if (!basicHelper.isNonZeroWeiValid(amountToStakeForBT)) {
      logger.error('Invalid wei amount to stake for BT', amountToStakeForBT.toString(10));
      process.exit(1);
    }
    if (!basicHelper.isNonZeroWeiValid(amountToStakeForSTP)) {
      logger.error('Invalid wei amount to stake for ST Prime', amountToStakeForSTP.toString(10));
      process.exit(1);
    }

    logger.step('** Starting stake mint for branded token for beneficiary reserve of BT Reserve:', oThis.reserveAddr);

    // NOTE: In real case, Member Company transfers ST to staker and then approve is called. To simulate this, foundation
    // is transfering ST to staker.
    logger.info('* Foundation transfers ST to BT Reserve');
    await fundManager.transferST(
        foundationAddr, foundationPassphrase, stakerAddr, oThis.amountToStakeInWeis,
        {tag: 'transferSTToBTReserve', returnType: 'txReceipt'}
    );

    logger.info('* Staker approves openSTValue contract');
    const approveResponse = await (new approveService()).perform();
    if (approveResponse.isFailure()) {
      process.exit(1);
    }

    const approveTransactionHash = approveResponse.data.transaction_hash;

    logger.info('* Get approval status and keep doing so till success');
    const approveReceiptResponse =  await contractInteractHelper.waitAndGetTransactionReceipt(web3Provider, approveTransactionHash, {});
    if (!approveReceiptResponse.isSuccess()) {
      logger.error('Approval receipt error ', approveReceiptResponse);
      process.exit(1);
    }

    logger.info('* Start stake for Branded Token');
    await (new startStakeService({
      beneficiary: oThis.reserveAddr,
      to_stake_amount: amountToStakeForBT,
      uuid: oThis.brandedTokenUuid
    })).perform();

    logger.info('* Waiting for credit of Branded Token to BT Reserve');
    await oThis._waitForBrandedTokenMint();

    logger.info('* Start stake for Simple Token Prime');
    await (new startStakeService({
      beneficiary: oThis.reserveAddr,
      to_stake_amount: amountToStakeForSTP,
      uuid: stPrimeUuid
    })).perform();

    logger.info('* Waiting for credit of Simple Token Prime to BT Reserve');
    await oThis._waitForSimpleTokenPrimeMint();

    return Promise.resolve(responseHelper.successWithData({}));
  }
791591
function signTransaction(priKeyBytes, transaction) {

  if (typeof priKeyBytes === 'string') {
    priKeyBytes = hexStr2byteArray(priKeyBytes);
  }

  let raw = transaction.getRawData();
  let rawBytes = raw.serializeBinary();
  let hashBytes = SHA256(rawBytes);
  let signBytes = ECKeySign(hashBytes, priKeyBytes);
  let uint8Array = new Uint8Array(signBytes);
  let count = raw.getContractList().length;
  for (let i = 0; i < count; i++) {
    transaction.addSignature(uint8Array);
  }

  return transaction;
}
47314
function blockEncrypt(input, inOffset, sessionKey) {

        if (input &&
          sessionKey &&
          utils.isAnArray(sessionKey) &&
          utils.isAnArray(input)) {

          input = new Uint8Array(input);
          var sBox = sessionKey[0]
            , sKey = sessionKey[1]

            /*eslint-disable no-plusplus*/
            , x0 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24

            , x1 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24

            , x2 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24

            , x3 = input[inOffset++] & 0xFF |
                   (input[inOffset++] & 0xFF) << 8 |
                   (input[inOffset++] & 0xFF) << 16 |
                   (input[inOffset++] & 0xFF) << 24
            /*eslint-enable no-plusplus*/

            , t0
            , t1
            , k = ROUND_SUBKEYS
            , R = 0;

          x0 ^= sKey[INPUT_WHITEN];
          x1 ^= sKey[INPUT_WHITEN + 1];
          x2 ^= sKey[INPUT_WHITEN + 2];
          x3 ^= sKey[INPUT_WHITEN + 3];
          for (R = 0; R < ROUNDS; R += 2) {

            t0 = fe32(sBox, x0, 0);
            t1 = fe32(sBox, x1, 3);
            /*eslint-disable no-plusplus*/
            x2 ^= t0 + t1 + sKey[k++];
            /*eslint-enable no-plusplus*/
            x2 = x2 >>> 1 | x2 << 31;
            x3 = x3 << 1 | x3 >>> 31;
            /*eslint-disable no-plusplus*/
            x3 ^= t0 + 2 * t1 + sKey[k++];
            /*eslint-enable no-plusplus*/

            t0 = fe32(sBox, x2, 0);
            t1 = fe32(sBox, x3, 3);
            /*eslint-disable no-plusplus*/
            x0 ^= t0 + t1 + sKey[k++];
            /*eslint-enable no-plusplus*/
            x0 = x0 >>> 1 | x0 << 31;
            x1 = x1 << 1 | x1 >>> 31;
            /*eslint-disable no-plusplus*/
            x1 ^= t0 + 2 * t1 + sKey[k++];
            /*eslint-enable no-plusplus*/
          }

          x2 ^= sKey[OUTPUT_WHITEN];
          x3 ^= sKey[OUTPUT_WHITEN + 1];
          x0 ^= sKey[OUTPUT_WHITEN + 2];
          x1 ^= sKey[OUTPUT_WHITEN + 3];

          return new Uint8Array([x2, x2 >>> 8, x2 >>> 16, x2 >>> 24,
             x3, x3 >>> 8, x3 >>> 16, x3 >>> 24,
             x0, x0 >>> 8, x0 >>> 16, x0 >>> 24,
             x1, x1 >>> 8, x1 >>> 16, x1 >>> 24]);
        }

        throw 'input block is not an array or sessionKey is incorrect';
      }
282903
function bitcount(key, start, end /* req */) {
  var req = typeof arguments[arguments.length - 1] === 'object'
    ? arguments[arguments.length - 1] : null
    , buf = this.getValueBuffer(key, req, true)
    , c = 0
    , count = 0
    , bytecount = 16;

  // no key or empty string
  if(buf === undefined || buf.length === 0) return 0;
  // got start/end range
  if(arguments.length >= 3) {
    if(start < 0) start = buf.length + start;
    if(end < 0) end = buf.length + end;
    if(start < 0) start = 0;
    if(end < 0) end = 0;
    if(end > buf.length) end = buf.length;
  }else{
    start = 0;
    end = buf.length;
  }

  if(start > end) return 0;

  // get the range we are inspecting
  buf = buf.slice(start, end + 1);

  function addBitCount(buf) {
    for(var i = 0;i < buf.length;i++) {
      if(buf[i] & 0x80) count++;
      if(buf[i] & 0x40) count++;
      if(buf[i] & 0x20) count++;
      if(buf[i] & 0x10) count++;
      if(buf[i] & 0x08) count++;
      if(buf[i] & 0x04) count++;
      if(buf[i] & 0x02) count++;
      if(buf[i] & 0x01) count++;
    }
  }

  // leading non-aligned bytes
  var mod = buf.length % bytecount;
  while(c < mod) {
    addBitCount(buf.slice(c, c + 1));
    c++;
  }

  // aligned bytes
  while(c < buf.length) {
    addBitCount(buf.slice(c, c + bytecount));
    c += bytecount;
  }
  return count;
}
483266
function ScryptPacket(passwd, salt, N, r, p, len) {
  Packet.call(this);
  this.passwd = passwd || null;
  this.salt = salt || null;
  this.N = N != null ? N : -1;
  this.r = r != null ? r : -1;
  this.p = p != null ? p : -1;
  this.len = len != null ? len : -1;
}
1291212
function decrypt(data) {
    return Promise.resolve().then(function() {
        var stm = new BinaryStream(data);
        var buffers = [];
        var blockIndex = 0, blockLength = 0, blockHash, totalLength = 0;

        var next = function() {
            blockIndex = stm.getUint32(true);
            blockHash = stm.readBytes(32);
            blockLength = stm.getUint32(true);
            if (blockLength > 0) {
                totalLength += blockLength;
                var blockData = stm.readBytes(blockLength);
                return CryptoEngine.sha256(blockData).then(function(calculatedHash) {
                    if (!ByteUtils.arrayBufferEquals(calculatedHash, blockHash)) {
                        throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'invalid hash block');
                    } else {
                        buffers.push(blockData);
                        return next();
                    }
                });
            } else {
                var ret = new Uint8Array(totalLength);
                var offset = 0;
                for (var i = 0; i < buffers.length; i++) {
                    ret.set(new Uint8Array(buffers[i]), offset);
                    offset += buffers[i].byteLength;
                }
                return ret.buffer;
            }
        };
        return next();
    });
}
804255
function (wallet) {
    var data = JSON.stringify(wallet, null, 2)
    var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0)
    var check = sha256(enc).toString('hex')

    // Throws if there is an encryption error
    Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () {
      throw 'Failed to confirm successful encryption when generating new wallet'
    })

    var postData = {
      guid: wallet.guid,
      sharedKey: wallet.sharedKey,
      length: enc.length,
      payload: enc,
      checksum: check,
      method: 'insert',
      format: 'plain'
    }

    if (email) postData.email = email

    return Blockchain.API.securePost('wallet', postData).then(function () {
      if (isHdWallet) {
        var account = wallet.hd_wallets[0].accounts[0]
        return { guid: wallet.guid, address: account.xpub, label: account.label }
      } else {
        var firstKey = wallet.keys[0]
        return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD }
      }
    })
  }
660261
function findBiggestUtxo(utxos) {
  var largestAmount = 0;
  var largestIndex = 0;

  for (var i = 0; i < utxos.length; i++) {
    var thisUtxo = utxos[i];

    if (thisUtxo.satoshis > largestAmount) {
      largestAmount = thisUtxo.satoshis;
      largestIndex = i;
    }
  }

  return utxos[largestIndex];
}
53149
function _createMiningInputBufferFromObject( objInput )
{
	let objInputCpy;
	let sInput;
	let bufSha512;
	let bufMd5;
	let bufRmd160;
	let bufSha384;

	if ( 'object' !== typeof objInput )
	{
		return null;
	}

	//	...
	objInputCpy	= {
		roundIndex		: objInput.roundIndex,
		firstTrustMEBall	: objInput.firstTrustMEBall,
		bits			: objInput.bits,
		publicSeed		: objInput.publicSeed,
		superNodeAuthor		: objInput.superNodeAuthor,
	};
	sInput		= JSON.stringify( objInputCpy );
	bufSha512	= _crypto.createHash( 'sha512' ).update( sInput, 'utf8' ).digest();
	bufMd5		= _crypto.createHash( 'md5' ).update( sInput, 'utf8' ).digest();
	bufRmd160	= _crypto.createHash( 'rmd160' ).update( sInput, 'utf8' ).digest();
	bufSha384	= _crypto.createHash( 'sha384' ).update( sInput, 'utf8' ).digest();

	return Buffer.concat( [ bufSha512, bufMd5, bufRmd160, bufSha384 ], 140 );
}
1212488
function WalletError(category, message, details, more) {
  more=more&&(': '+more)||''
  Error.call(this);
  Error.captureStackTrace(this, this.constructor);
  var status=parseInt(message),code=parseInt(details);
  this.category = category;
  this.code=code||undefined
  this.message = !isNaN(status)&&(messages.getStatus(status)+more)||message;
  this.details = code&&messages.getDescription(code)||details;
  this.name = this.constructor.name;
}
1122013
function _update(s, w, bytes) {
  // consume 512 bit (64 byte) chunks
  var t, a, b, c, d, f, r, i;
  var len = bytes.length();
  while(len >= 64) {
    // initialize hash value for this chunk
    a = s.h0;
    b = s.h1;
    c = s.h2;
    d = s.h3;

    // round 1
    for(i = 0; i < 16; ++i) {
      w[i] = bytes.getInt32Le();
      f = d ^ (b & (c ^ d));
      t = (a + f + _k[i] + w[i]);
      r = _r[i];
      a = d;
      d = c;
      c = b;
      b += (t << r) | (t >>> (32 - r));
    }
    // round 2
    for(; i < 32; ++i) {
      f = c ^ (d & (b ^ c));
      t = (a + f + _k[i] + w[_g[i]]);
      r = _r[i];
      a = d;
      d = c;
      c = b;
      b += (t << r) | (t >>> (32 - r));
    }
    // round 3
    for(; i < 48; ++i) {
      f = b ^ c ^ d;
      t = (a + f + _k[i] + w[_g[i]]);
      r = _r[i];
      a = d;
      d = c;
      c = b;
      b += (t << r) | (t >>> (32 - r));
    }
    // round 4
    for(; i < 64; ++i) {
      f = c ^ (b | ~d);
      t = (a + f + _k[i] + w[_g[i]]);
      r = _r[i];
      a = d;
      d = c;
      c = b;
      b += (t << r) | (t >>> (32 - r));
    }

    // update hash state
    s.h0 = (s.h0 + a) | 0;
    s.h1 = (s.h1 + b) | 0;
    s.h2 = (s.h2 + c) | 0;
    s.h3 = (s.h3 + d) | 0;

    len -= 64;
  }
}
176341
function checksum(src, algorithm='sha256', outputFormat='hex'){
    return new Promise(async function(resolve, reject){
        // hash engine
        const hash = _crypto.createHash(algorithm);

        // events
        hash.on('readable', function(){
            // get hashsum
            const sum = hash.read();

            // data available ?
            if (!sum){
                return;
            }

            // hex, base64 or buffer
            switch (outputFormat){
                case 'base64':
                    resolve(sum.toString('base64'));
                    break;
                case 'raw':
                case 'buffer':
                    resolve(sum);
                    break;
                default:
                    resolve(sum.toString('hex'));
                    break;
            }
        });
        hash.on('error', function(e){
            reject(e);
        })

        try{
            // open file input stream
            const input = await _fInputStream(src);

             // stream hashing
            input.pipe(hash);
        }catch(e){
            reject(e);
        }
    });
}
244982
function generate(entropy) {
  if (typeof entropy !== 'string') { throw new Error(`[ethjs-account] while generating account, invalid input type: '${typeof(entropy)}' should be type 'String'.`); }
  if (entropy.length < 32) { throw new Error(`[ethjs-account] while generating account, entropy value not random and long enough, should be at least 32 characters of random information, is only ${entropy.length}`); }

  return privateToAccount(sha3(`${randomhex(16)}${sha3(`${randomhex(32)}${entropy}`)}${randomhex(32)}`));
}
230707
function(_config) {
        var self = this;

        if(!_config) {
            throw new Error("You must give bitcoinaddress config object");
        }
        this.config = _config;
        $ = this.config.jQuery || jQuery;
        this.scan();
        this.initUX();
    }
1048932
function _makeBitReversalTable() {
    var i = 0,
        j = 0,
        k = 0;
    _bitrev[0] = 0;
    while (++i < _n) {
        k = _n >> 1;
        while (k <= j) {
            j -= k;
            k >>= 1;
        }
        j += k;
        _bitrev[i] = j;
    }
}