Esempio n. 1
0
Wire.prototype.port = function (port) {
  this._debug('port %d', port)
  var message = Buffer.from(MESSAGE_PORT)
  message.writeUInt16BE(port, 5)
  this._push(message)
}
Esempio n. 2
0
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = Buffer.from(chunk, encoding);
  }
  return chunk;
}
Esempio n. 3
0
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
Esempio n. 4
0
 it('should 415 on unknown charset', function (done) {
   var test = request(this.server).post('/')
   test.set('Content-Type', 'text/plain; charset=x-bogus')
   test.write(Buffer.from('00000000', 'hex'))
   test.expect(415, 'unsupported charset "X-BOGUS"', done)
 })
stream._read = function (size) {
  reads++;
  size = Math.min(size, total);
  total -= size;
  if (size === 0) stream.push(null);else stream.push(bufferShim.allocUnsafe(size));
};
/*
  connection.query('SELECT repeat("a", 60000000) as qqq', function (err, res) {
    console.log(err);
    console.log(err, res[0].qqq.length);
    connection.end();
  });
  return;
*/

var assert = require('assert');
var Buffer = require('safe-buffer').Buffer;

var table = 'insert_large_test';
var length = 35777416;
var content = Buffer.allocUnsafe(length); // > 16 megabytes
var content1 = Buffer.allocUnsafe(length); // > 16 megabytes

// this is to force compressed packed to be larger than uncompressed
for (var i = 0; i < content.length; ++i) {
  content[i] = Math.floor(Math.random() * 256);
  content1[i] = Math.floor(Math.random() * 256);

  // low entropy version, compressed < uncompressed
  if (i < length / 2) {
    content1[i] = 100;
  }
}

var result, result2, result3, result4;
Esempio n. 7
0
function GHASH (key) {
  this.h = key
  this.state = Buffer.alloc(16, 0)
  this.cache = Buffer.allocUnsafe(0)
}
Esempio n. 8
0
exports.privateKeyNegate = function (privateKey) {
  var bn = new BN(privateKey)
  return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32)
}
Esempio n. 9
0
DHT.prototype._generateToken = function (host, secret) {
  if (!secret) secret = this._secrets[0]
  return crypto.createHash('sha1').update(Buffer.from(host)).update(secret).digest()
}
Esempio n. 10
0
    noncefn = function (counter) {
      var nonce = getNonce(message, privateKey, null, data, counter)
      if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL)

      return new BN(nonce)
    }
Esempio n. 11
0
exports.privateKeyExport = function (privateKey, compressed) {
  var d = new BN(privateKey)
  if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL)

  return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true))
}
Esempio n. 12
0
exports.publicKeyConvert = function (publicKey, compressed) {
  var pair = loadPublicKey(publicKey)
  if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)

  return Buffer.from(pair.getPublic(compressed, true))
}
Esempio n. 13
0
exports.publicKeyCreate = function (privateKey, compressed) {
  var d = new BN(privateKey)
  if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL)

  return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true))
}
 const input = [...Array(500).keys()].map(() => Buffer.from('payload'))
Esempio n. 15
0
 return function verify(thing, signature, secret) {
   var computedSig = createHmacSigner(bits)(thing, secret);
   return bufferEqual(Buffer.from(signature), Buffer.from(computedSig));
 }
Esempio n. 16
0
function toBuffer (str) {
  if (Buffer.isBuffer(str)) return str
  if (typeof str === 'string') return Buffer.from(str, 'hex')
  throw new Error('Pass a buffer or a string')
}
Esempio n. 17
0
/**
 * Decode buffers into utf-8 string
 *
 * @return  Promise
 */
function consumeBody (body) {
  if (this[DISTURBED]) {
    return Body.Promise.reject(new Error(`body used already for: ${this.url}`))
  }

  this[DISTURBED] = true

  // body is null
  if (this.body === null) {
    return Body.Promise.resolve(Buffer.alloc(0))
  }

  // body is string
  if (typeof this.body === 'string') {
    return Body.Promise.resolve(Buffer.from(this.body))
  }

  // body is blob
  if (this.body instanceof Blob) {
    return Body.Promise.resolve(this.body[BUFFER])
  }

  // body is buffer
  if (Buffer.isBuffer(this.body)) {
    return Body.Promise.resolve(this.body)
  }

  // istanbul ignore if: should never happen
  if (!(this.body instanceof Stream)) {
    return Body.Promise.resolve(Buffer.alloc(0))
  }

  // body is stream
  // get ready to actually consume the body
  let accum = []
  let accumBytes = 0
  let abort = false

  return new Body.Promise((resolve, reject) => {
    let resTimeout

    // allow timeout on slow response body
    if (this.timeout) {
      resTimeout = setTimeout(() => {
        abort = true
        reject(new FetchError(`Response timeout while trying to fetch ${this.url} (over ${this.timeout}ms)`, 'body-timeout'))
      }, this.timeout)
    }

    // handle stream error, such as incorrect content-encoding
    this.body.on('error', err => {
      reject(new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, 'system', err))
    })

    this.body.on('data', chunk => {
      if (abort || chunk === null) {
        return
      }

      if (this.size && accumBytes + chunk.length > this.size) {
        abort = true
        reject(new FetchError(`content size at ${this.url} over limit: ${this.size}`, 'max-size'))
        return
      }

      accumBytes += chunk.length
      accum.push(chunk)
    })

    this.body.on('end', () => {
      if (abort) {
        return
      }

      clearTimeout(resTimeout)
      resolve(Buffer.concat(accum))
    })
  })
}
Esempio n. 18
0
var Buffer = require('safe-buffer').Buffer
var Client = require('../')
var common = require('./common')
var test = require('tape')
// var wrtc = require('electron-webrtc')()

// var wrtcReady = false
// wrtc.electronDaemon.once('ready', function () {
//   wrtcReady = true
// })

var infoHash = '4cb67059ed6bd08362da625b3ae77f6f4a075705'
var peerId = Buffer.from('01234567890123456789')
var peerId2 = Buffer.from('12345678901234567890')

function serverTest (t, serverType, serverFamily) {
  t.plan(30)

  var hostname = serverFamily === 'inet6'
    ? '[::1]'
    : '127.0.0.1'
  var clientIp = serverFamily === 'inet6'
    ? '::1'
    : '127.0.0.1'

  common.createServer(t, serverType, function (server) {
    var port = server[serverType].address().port
    var announceUrl = serverType + '://' + hostname + ':' + port + '/announce'

    var client1 = new Client({
      infoHash: infoHash,
Esempio n. 19
0
var Buffer = require('safe-buffer').Buffer
var ZEROES = Buffer.alloc(16, 0)

function toArray (buf) {
  return [
    buf.readUInt32BE(0),
    buf.readUInt32BE(4),
    buf.readUInt32BE(8),
    buf.readUInt32BE(12)
  ]
}

function fromArray (out) {
  var buf = Buffer.allocUnsafe(16)
  buf.writeUInt32BE(out[0] >>> 0, 0)
  buf.writeUInt32BE(out[1] >>> 0, 4)
  buf.writeUInt32BE(out[2] >>> 0, 8)
  buf.writeUInt32BE(out[3] >>> 0, 12)
  return buf
}

function GHASH (key) {
  this.h = key
  this.state = Buffer.alloc(16, 0)
  this.cache = Buffer.allocUnsafe(0)
}

// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
// by Juho Vähä-Herttua
GHASH.prototype.ghash = function (block) {
  var i = -1
Esempio n. 20
0
function decodeBase64 (str) {
  return Buffer.from(str, 'base64').toString()
}
Esempio n. 21
0
 it('should parse codepage charsets', function (done) {
   var test = request(this.server).post('/')
   test.set('Content-Type', 'text/plain; charset=koi8-r')
   test.write(Buffer.from('6e616d6520697320cec5d4', 'hex'))
   test.expect(200, '"name is нет"', done)
 })
Esempio n. 22
0
/* Header */
protocol.CMD_SHIFT = 4
protocol.CMD_MASK = 0xF0
protocol.DUP_MASK = 0x08
protocol.QOS_MASK = 0x03
protocol.QOS_SHIFT = 1
protocol.RETAIN_MASK = 0x01

/* Length */
protocol.LENGTH_MASK = 0x7F
protocol.LENGTH_FIN_MASK = 0x80

/* Connack */
protocol.SESSIONPRESENT_MASK = 0x01
protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])

/* Connect */
protocol.USERNAME_MASK = 0x80
protocol.PASSWORD_MASK = 0x40
protocol.WILL_RETAIN_MASK = 0x20
protocol.WILL_QOS_MASK = 0x18
protocol.WILL_QOS_SHIFT = 3
protocol.WILL_FLAG_MASK = 0x04
protocol.CLEAN_SESSION_MASK = 0x02
protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])

function genHeader (type) {
  return [0, 1, 2].map(function (qos) {
    return [0, 1].map(function (dup) {
Esempio n. 23
0
 it('should parse without encoding', function (done) {
   var test = request(this.server).post('/')
   test.set('Content-Type', 'text/plain')
   test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))
   test.expect(200, '"name is 论"', done)
 })
Esempio n. 24
0
protocol.QOS = [0, 1, 2].map(function (qos) {
  return Buffer.from([qos])
})
Esempio n. 25
0
function writeCompressed (buffer) {

  // http://dev.mysql.com/doc/internals/en/example-several-mysql-packets.html
  // note: sending a MySQL Packet of the size 2^24−5 to 2^24−1 via compression
  // leads to at least one extra compressed packet.
  // (this is because "length of the packet before compression" need to fit
  // into 3 byte unsigned int. "length of the packet before compression" includes
  // 4 byte packet header, hence 2^24−5)
  var MAX_COMPRESSED_LENGTH = 16777210;
  var start;
  if (buffer.length > MAX_COMPRESSED_LENGTH) {
    for (start = 0; start < buffer.length; start += MAX_COMPRESSED_LENGTH) {
      writeCompressed.call(this, buffer.slice(start, start + MAX_COMPRESSED_LENGTH));
    }
    return;
  }

  var connection = this;

  var packetLen = buffer.length;
  var compressHeader = Buffer.allocUnsafe(7);

  // seqqueue is used here because zlib async execution is routed via thread pool
  // internally and when we have multiple compressed packets arriving we need
  // to assemble uncompressed result sequentially
  (function (seqId) {
    connection.deflateQueue.push(function (task) {
      zlib.deflate(buffer, function (err, compressed) {
        if (err) {
          connection._handleFatalError(err);
          return;
        }
        var compressedLength = compressed.length;

        if (compressedLength < packetLen) {
          compressHeader.writeUInt8(compressedLength & 0xff, 0);
          compressHeader.writeUInt16LE(compressedLength >> 8, 1);
          compressHeader.writeUInt8(seqId, 3);
          compressHeader.writeUInt8(packetLen & 0xff, 4);
          compressHeader.writeUInt16LE(packetLen >> 8, 5);
          connection.writeUncompressed(compressHeader);
          connection.writeUncompressed(compressed);
        } else {
          // http://dev.mysql.com/doc/internals/en/uncompressed-payload.html
          // To send an uncompressed payload:
          //   - set length of payload before compression to 0
          //   - the compressed payload contains the uncompressed payload instead.
          compressedLength = packetLen;
          packetLen = 0;
          compressHeader.writeUInt8(compressedLength & 0xff, 0);
          compressHeader.writeUInt16LE(compressedLength >> 8, 1);
          compressHeader.writeUInt8(seqId, 3);
          compressHeader.writeUInt8(packetLen & 0xff, 4);
          compressHeader.writeUInt16LE(packetLen >> 8, 5);
          connection.writeUncompressed(compressHeader);
          connection.writeUncompressed(buffer);
        }
        task.done();
      });
    });
  })(connection.compressedSequenceId);
  connection._bumpCompressedSequenceId(1);
}
Esempio n. 26
0
var Buffer = require('safe-buffer').Buffer
var createHmac = require('create-hmac')
var typeforce = require('typeforce')
var types = require('./types')

var BigInteger = require('bigi')
var ECSignature = require('./ecsignature')

var ZERO = Buffer.alloc(1, 0)
var ONE = Buffer.alloc(1, 1)

var ecurve = require('ecurve')
var secp256k1 = ecurve.getCurveByName('secp256k1')

// https://tools.ietf.org/html/rfc6979#section-3.2
function deterministicGenerateK (hash, x, checkSig) {
  typeforce(types.tuple(
    types.Hash256bit,
    types.Buffer256bit,
    types.Function
  ), arguments)

  // Step A, ignored as hash already provided
  // Step B
  // Step C
  var k = Buffer.alloc(32, 0)
  var v = Buffer.alloc(32, 1)

  // Step D
  k = createHmac('sha256', k)
    .update(v)
Esempio n. 27
0
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
Esempio n. 28
0
function bufferOrString(obj) {
  return Buffer.isBuffer(obj) || typeof obj === 'string';
}
function hashEventSignature(eventName) {
  return speedomatic.formatInt256(keccak256(Buffer.from(eventName, "utf8")).toString("hex"));
}
Esempio n. 30
0
Wire.prototype.bitfield = function (bitfield) {
  this._debug('bitfield')
  if (!Buffer.isBuffer(bitfield)) bitfield = bitfield.buffer
  this._message(5, [], bitfield)
}