How to use bencode - 10 common examples

To help you get started, we’ve selected a few bencode examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Sheraff / tvshows-alfred-workflow / node_modules / peerflix / node_modules / torrent-stream / node_modules / bittorrent-tracker / server.js View on Github external
function error (message) {
    debug('sent error %s', message)
    res.end(bencode.encode({
      'failure reason': message
    }))

    // even though it's an error for the client, it's just a warning for the server.
    // don't crash the server because a client sent bad data :)
    self.emit('warning', new Error(message))
  }
}
github jaruba / PowderPlayer / node_modules / peerflix / node_modules / torrent-stream / node_modules / parse-torrent / node_modules / parse-torrent-file / index.js View on Github external
ensure(torrent.info.name, 'info.name')
  ensure(torrent.info['piece length'], 'info[\'piece length\']')
  ensure(torrent.info.pieces, 'info.pieces')

  if (torrent.info.files) {
    torrent.info.files.forEach(function (file) {
      ensure(typeof file.length === 'number', 'info.files[0].length')
      ensure(file.path, 'info.files[0].path')
    })
  } else {
    ensure(typeof torrent.info.length === 'number', 'info.length')
  }

  var result = {}
  result.info = torrent.info
  result.infoBuffer = bencode.encode(torrent.info)
  result.infoHash = sha1.sync(result.infoBuffer)

  result.name = torrent.info.name.toString()
  result.private = !!torrent.info.private

  if (torrent['creation date']) result.created = new Date(torrent['creation date'] * 1000)

  if (Buffer.isBuffer(torrent.comment)) result.comment = torrent.comment.toString()

  // announce/announce-list may be missing if metadata fetched via ut_metadata extension
  var announce = torrent['announce-list']
  if (!announce) {
    if (torrent.announce) {
      announce = [[torrent.announce]]
    } else {
      announce = []
github webtorrent / parse-torrent / index.js View on Github external
ensure(torrent.info['name.utf-8'] || torrent.info.name, 'info.name')
  ensure(torrent.info['piece length'], 'info[\'piece length\']')
  ensure(torrent.info.pieces, 'info.pieces')

  if (torrent.info.files) {
    torrent.info.files.forEach(file => {
      ensure(typeof file.length === 'number', 'info.files[0].length')
      ensure(file['path.utf-8'] || file.path, 'info.files[0].path')
    })
  } else {
    ensure(typeof torrent.info.length === 'number', 'info.length')
  }

  const result = {
    info: torrent.info,
    infoBuffer: bencode.encode(torrent.info),
    name: (torrent.info['name.utf-8'] || torrent.info.name).toString(),
    announce: []
  }

  result.infoHash = sha1.sync(result.infoBuffer)
  result.infoHashBuffer = Buffer.from(result.infoHash, 'hex')

  if (torrent.info.private !== undefined) result.private = !!torrent.info.private

  if (torrent['creation date']) result.created = new Date(torrent['creation date'] * 1000)
  if (torrent['created by']) result.createdBy = torrent['created by'].toString()

  if (Buffer.isBuffer(torrent.comment)) result.comment = torrent.comment.toString()

  // announce and announce-list will be missing if metadata fetched via ut_metadata
  if (Array.isArray(torrent['announce-list']) && torrent['announce-list'].length > 0) {
github webtorrent / ut_metadata / index.js View on Github external
setMetadata (metadata) {
      if (this._metadataComplete) return true
      debug('set metadata')

      // if full torrent dictionary was passed in, pull out just `info` key
      try {
        const info = bencode.decode(metadata).info
        if (info) {
          metadata = bencode.encode(info)
        }
      } catch (err) {}

      // check hash
      if (this._infoHash && this._infoHash !== sha1.sync(metadata)) {
        return false
      }

      this.cancel()

      this.metadata = metadata
      this._metadataComplete = true
      this._metadataSize = this.metadata.length
      this._wire.extendedHandshake.metadata_size = this._metadataSize
github chr15m / bugout / index.js View on Github external
function onMessage(bugout, identifier, wire, message) {
  // hash to reference incoming message
  var hash = toHex(nacl.hash(message).slice(16));
  var t = now();
  debug("raw message", identifier, message.length, hash);
  if (!bugout.seen[hash]) {
    var unpacked = bencode.decode(message);
    // if this is an encrypted packet first try to decrypt it
    if (unpacked.e && unpacked.n && unpacked.ek) {
      var ek = unpacked.ek.toString();
      debug("message encrypted by", ek, unpacked);
      var decrypted = nacl.box.open(unpacked.e, unpacked.n, bs58.decode(ek), bugout.keyPairEncrypt.secretKey);
      if (decrypted) {
        unpacked = bencode.decode(decrypted);
      } else {
        unpacked = null;
      }
    }
    // if there's no data decryption failed
    if (unpacked && unpacked.p) {
      debug("unpacked message", unpacked);
      var packet = bencode.decode(unpacked.p);
      var pk = packet.pk.toString();
github webtorrent / ut_metadata / index.js View on Github external
onMessage (buf) {
      let dict
      let trailer
      try {
        const str = buf.toString()
        const trailerIndex = str.indexOf('ee') + 2
        dict = bencode.decode(str.substring(0, trailerIndex))
        trailer = buf.slice(trailerIndex)
      } catch (err) {
        // drop invalid messages
        return
      }

      switch (dict.msg_type) {
        case 0:
          // ut_metadata request (from peer)
          // example: { 'msg_type': 0, 'piece': 0 }
          this._onRequest(dict.piece)
          break
        case 1:
          // ut_metadata data (in response to our request)
          // example: { 'msg_type': 1, 'piece': 0, 'total_size': 3425 }
          this._onData(dict.piece, trailer, dict.total_size)
github fanpei91 / torsniff / src / wire.js View on Github external
_onDone(metadata){
    try {
      let info = bencode.decode(metadata).info;
      if (info) {
        metadata = bencode.encode(info);
      }
    }
    catch (err) {
      return;
    }
    let infohash = crypto.createHash('sha1').update(metadata).digest('hex');
    if (this._infohash.toString('hex') !== infohash ) {
      return false;
    }
    this.emit('metadata', {info: bencode.decode(metadata)}, this._infohash);
  }
github bunsenbrowser / bunsen / www / nodejs-project / node_modules / bittorrent-dht / client.js View on Github external
var token = a.token
  if (!token) return

  if (!this._validateToken(host, token)) {
    return this._rpc.error(peer, query, [203, 'cannot `put` with bad token'])
  }
  if (v.length > 1000) {
    return this._rpc.error(peer, query, [205, 'data payload too large'])
  }

  var isMutable = !!(a.k || a.sig)
  if (isMutable && !a.k && !a.sig) return

  var key = isMutable
    ? this._hash(a.salt ? Buffer.concat([a.k, a.salt]) : a.k)
    : this._hash(bencode.encode(v))
  var keyHex = key.toString('hex')

  this.emit('put', key, v)

  if (isMutable) {
    if (!this._verify) return this._rpc.error(peer, query, [400, 'verification not supported'])
    if (!this._verify(a.sig, encodeSigData(a), a.k)) return
    var prev = this._values.get(keyHex)
    if (prev && typeof a.cas === 'number' && prev.seq !== a.cas) {
      return this._rpc.error(peer, query, [301, 'CAS mismatch, re-read and try again'])
    }
    if (prev && typeof prev.seq === 'number' && !(a.seq > prev.seq)) {
      return this._rpc.error(peer, query, [302, 'sequence number less than current'])
    }
    this._values.set(keyHex, {v: v, k: a.k, salt: a.salt, sig: a.sig, seq: a.seq, id: id})
  } else {
github AlphaReign / scraper / src / wire.js View on Github external
Wire.prototype._onDone = function(metadata) {
	try {
		var info = bencode.decode(metadata).info;
		if (info) {
			metadata = bencode.encode(info);
		}
	} catch (err) {
		this._fail();
		return;
	}
	var infohash = crypto
		.createHash('sha1')
		.update(metadata)
		.digest('hex');
	if (this._infohash.toString('hex') != infohash) {
		this._fail();
		return false;
	}
	this.emit('metadata', { info: bencode.decode(metadata) }, this._infohash);
};
github Ayms / torrent-live / node_modules / bittorrent-dht / client.js View on Github external
DHT.prototype._onData = function (data, rinfo) {
  var self = this
  var addr = rinfo.address + ':' + rinfo.port
  
  try {
    var message = bencode.decode(data)
    if (!message) throw new Error('message is empty')
  } catch (err) {
    //console.log('bad message from ' + addr + ' ' + err.message)
	//modif
	spies.call(self,('receiving bad message from know spy '+addr),addr);
    return
  }

  debug('got message from ' + addr + ' ' + JSON.stringify(message))

  if (message.y) {
    var type = message.y.toString()
  }
  
  //modif
  spies.call(self,'receiving message from know spy '+addr+' message type '+type,addr);

bencode

Bencode de/encoder

MIT
Latest version published 1 year ago

Package Health Score

65 / 100
Full package analysis

Popular bencode functions