net: classify.

This commit is contained in:
Christopher Jeffrey 2017-11-16 19:37:09 -08:00
parent 8be995bd78
commit 4ebfb5d9ff
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
7 changed files with 9518 additions and 9467 deletions

View File

@ -26,14 +26,10 @@ const packets = require('./packets');
const {encoding} = bio;
/**
* BIP150
* Represents a BIP150 input/output stream.
* @alias module:net.BIP150
* @constructor
* @param {BIP151} bip151
* @param {String} host
* @param {Boolean} outbound
* @param {AuthDB} db
* @param {Buffer} key - Identity key.
* @extends EventEmitter
* @property {BIP151} bip151
* @property {BIP151Stream} input
* @property {BIP151Stream} output
@ -51,11 +47,19 @@ const {encoding} = bio;
* @property {Boolean} completed
*/
function BIP150(bip151, host, outbound, db, key) {
if (!(this instanceof BIP150))
return new BIP150(bip151, host, outbound, db, key);
class BIP150 extends EventEmitter {
/**
* Create a BIP150 input/output stream.
* @constructor
* @param {BIP151} bip151
* @param {String} host
* @param {Boolean} outbound
* @param {AuthDB} db
* @param {Buffer} key - Identity key.
*/
EventEmitter.call(this);
constructor(bip151, host, outbound, db, key) {
super();
assert(bip151, 'BIP150 requires BIP151.');
assert(typeof host === 'string', 'Hostname required.');
@ -86,17 +90,15 @@ function BIP150(bip151, host, outbound, db, key) {
this.init();
}
Object.setPrototypeOf(BIP150.prototype, EventEmitter.prototype);
/**
* Initialize BIP150.
* @private
*/
BIP150.prototype.init = function init() {
init() {
if (this.outbound)
this.peerIdentity = this.db.getKnown(this.hostname);
};
}
/**
* Test whether the state should be
@ -105,11 +107,11 @@ BIP150.prototype.init = function init() {
* @returns {Boolean}
*/
BIP150.prototype.isAuthed = function isAuthed() {
isAuthed() {
if (this.outbound)
return this.challengeSent && this.challengeReceived;
return this.challengeReceived && this.replyReceived;
};
}
/**
* Handle a received challenge hash.
@ -119,7 +121,7 @@ BIP150.prototype.isAuthed = function isAuthed() {
* @throws on auth failure
*/
BIP150.prototype.challenge = function challenge(hash) {
challenge(hash) {
const type = this.outbound ? 'r' : 'i';
assert(this.bip151.handshake, 'No BIP151 handshake before challenge.');
@ -143,7 +145,7 @@ BIP150.prototype.challenge = function challenge(hash) {
// authreply
return secp256k1.fromDER(sig);
};
}
/**
* Handle a received reply signature.
@ -153,7 +155,7 @@ BIP150.prototype.challenge = function challenge(hash) {
* @throws on auth failure
*/
BIP150.prototype.reply = function reply(data) {
reply(data) {
const type = this.outbound ? 'i' : 'r';
assert(this.challengeSent, 'Unsolicited reply.');
@ -184,7 +186,7 @@ BIP150.prototype.reply = function reply(data) {
// authpropose
return this.hash(this.input.sid, 'p', this.publicKey);
};
}
/**
* Handle a received propose hash.
@ -193,7 +195,7 @@ BIP150.prototype.reply = function reply(data) {
* @returns {Buffer}
*/
BIP150.prototype.propose = function propose(hash) {
propose(hash) {
assert(!this.outbound, 'Outbound peer tried to propose.');
assert(!this.challengeSent, 'Unsolicited propose.');
assert(!this.proposeReceived, 'Peer proposed twice.');
@ -213,7 +215,7 @@ BIP150.prototype.propose = function propose(hash) {
// authchallenge
return this.hash(this.output.sid, 'r', this.peerIdentity);
};
}
/**
* Create initial authchallenge hash
@ -222,7 +224,7 @@ BIP150.prototype.propose = function propose(hash) {
* @returns {AuthChallengePacket}
*/
BIP150.prototype.toChallenge = function toChallenge() {
toChallenge() {
assert(this.bip151.handshake, 'No BIP151 handshake before challenge.');
assert(this.outbound, 'Cannot challenge an inbound connection.');
assert(this.peerIdentity, 'Cannot challenge without a peer identity.');
@ -233,7 +235,7 @@ BIP150.prototype.toChallenge = function toChallenge() {
this.challengeSent = true;
return new packets.AuthChallengePacket(msg);
};
}
/**
* Derive new cipher keys based on
@ -246,42 +248,42 @@ BIP150.prototype.toChallenge = function toChallenge() {
* @returns {Buffer}
*/
BIP150.prototype.rekey = function rekey(sid, key, req, res) {
rekey(sid, key, req, res) {
const seed = Buffer.allocUnsafe(130);
sid.copy(seed, 0);
key.copy(seed, 32);
req.copy(seed, 64);
res.copy(seed, 97);
return hash256.digest(seed);
};
}
/**
* Rekey the BIP151 input stream
* using BIP150-style derivation.
*/
BIP150.prototype.rekeyInput = function rekeyInput() {
rekeyInput() {
const stream = this.input;
const req = this.peerIdentity;
const res = this.publicKey;
const k1 = this.rekey(stream.sid, stream.k1, req, res);
const k2 = this.rekey(stream.sid, stream.k2, req, res);
stream.rekey(k1, k2);
};
}
/**
* Rekey the BIP151 output stream
* using BIP150-style derivation.
*/
BIP150.prototype.rekeyOutput = function rekeyOutput() {
rekeyOutput() {
const stream = this.output;
const req = this.publicKey;
const res = this.peerIdentity;
const k1 = this.rekey(stream.sid, stream.k1, req, res);
const k2 = this.rekey(stream.sid, stream.k2, req, res);
stream.rekey(k1, k2);
};
}
/**
* Create a hash using the session ID.
@ -291,13 +293,13 @@ BIP150.prototype.rekeyOutput = function rekeyOutput() {
* @returns {Buffer}
*/
BIP150.prototype.hash = function hash(sid, ch, key) {
hash(sid, ch, key) {
const data = Buffer.allocUnsafe(66);
sid.copy(data, 0);
data[32] = ch.charCodeAt(0);
key.copy(data, 33);
return hash256.digest(data);
};
}
/**
* Find an authorized peer in the Auth
@ -309,7 +311,7 @@ BIP150.prototype.hash = function hash(sid, ch, key) {
* @returns {Buffer|null}
*/
BIP150.prototype.findAuthorized = function findAuthorized(hash) {
findAuthorized(hash) {
// Scary O(n) stuff.
for (const key of this.db.authorized) {
const msg = this.hash(this.output.sid, 'p', key);
@ -322,19 +324,19 @@ BIP150.prototype.findAuthorized = function findAuthorized(hash) {
}
return null;
};
}
/**
* Destroy the BIP150 stream and
* any current running wait job.
*/
BIP150.prototype.destroy = function destroy() {
destroy() {
if (!this.job)
return;
this.reject(new Error('BIP150 stream was destroyed.'));
};
}
/**
* Cleanup wait job.
@ -342,7 +344,7 @@ BIP150.prototype.destroy = function destroy() {
* @returns {Job}
*/
BIP150.prototype.cleanup = function cleanup() {
cleanup() {
const job = this.job;
assert(!this.completed, 'Already completed.');
@ -362,7 +364,7 @@ BIP150.prototype.cleanup = function cleanup() {
}
return job;
};
}
/**
* Resolve the current wait job.
@ -370,10 +372,10 @@ BIP150.prototype.cleanup = function cleanup() {
* @param {Object} result
*/
BIP150.prototype.resolve = function resolve(result) {
resolve(result) {
const job = this.cleanup();
job.resolve(result);
};
}
/**
* Reject the current wait job.
@ -381,10 +383,10 @@ BIP150.prototype.resolve = function resolve(result) {
* @param {Error} err
*/
BIP150.prototype.reject = function reject(err) {
reject(err) {
const job = this.cleanup();
job.reject(err);
};
}
/**
* Wait for handshake to complete.
@ -392,11 +394,11 @@ BIP150.prototype.reject = function reject(err) {
* @returns {Promise}
*/
BIP150.prototype.wait = function wait(timeout) {
wait(timeout) {
return new Promise((resolve, reject) => {
this._wait(timeout, resolve, reject);
});
};
}
/**
* Wait for handshake to complete.
@ -406,7 +408,7 @@ BIP150.prototype.wait = function wait(timeout) {
* @param {Function} reject
*/
BIP150.prototype._wait = function _wait(timeout, resolve, reject) {
_wait(timeout, resolve, reject) {
assert(!this.auth, 'Cannot wait for init after handshake.');
this.job = { resolve, reject };
@ -422,7 +424,7 @@ BIP150.prototype._wait = function _wait(timeout, resolve, reject) {
this.onAuth = this.resolve.bind(this);
this.once('auth', this.onAuth);
};
}
/**
* Serialize the peer's identity
@ -430,10 +432,10 @@ BIP150.prototype._wait = function _wait(timeout, resolve, reject) {
* @returns {Base58String}
*/
BIP150.prototype.getAddress = function getAddress() {
getAddress() {
assert(this.peerIdentity, 'Cannot serialize address.');
return BIP150.address(this.peerIdentity);
};
}
/**
* Serialize an identity key as a
@ -441,25 +443,28 @@ BIP150.prototype.getAddress = function getAddress() {
* @returns {Base58String}
*/
BIP150.address = function address(key) {
static address(key) {
const bw = bio.write(27);
bw.writeU8(0x0f);
bw.writeU16BE(0xff01);
bw.writeBytes(hash160.digest(key));
bw.writeChecksum(hash256.digest);
return base58.encode(bw.render());
};
}
}
/**
* AuthDB
* @alias module:net.AuthDB
*/
class AuthDB {
/**
* Create an auth DB.
* @constructor
*/
function AuthDB(options) {
if (!(this instanceof AuthDB))
return new AuthDB(options);
constructor(options) {
this.logger = Logger.global;
this.resolve = dns.lookup;
this.prefix = null;
@ -476,7 +481,7 @@ function AuthDB(options) {
* @param {Object} options
*/
AuthDB.prototype.init = function init(options) {
init(options) {
if (!options)
return;
@ -504,7 +509,7 @@ AuthDB.prototype.init = function init(options) {
assert(typeof options.prefix === 'string');
this.prefix = options.prefix;
}
};
}
/**
* Open auth database (lookup known peers).
@ -512,11 +517,11 @@ AuthDB.prototype.init = function init(options) {
* @returns {Promise}
*/
AuthDB.prototype.open = async function open() {
async open() {
await this.readKnown();
await this.readAuth();
await this.lookup();
};
}
/**
* Close auth database.
@ -524,9 +529,9 @@ AuthDB.prototype.open = async function open() {
* @returns {Promise}
*/
AuthDB.prototype.close = async function close() {
async close() {
;
};
}
/**
* Add a known peer.
@ -534,7 +539,7 @@ AuthDB.prototype.close = async function close() {
* @param {Buffer} key - Identity Key
*/
AuthDB.prototype.addKnown = function addKnown(host, key) {
addKnown(host, key) {
assert(typeof host === 'string',
'Known host must be a string.');
@ -550,44 +555,44 @@ AuthDB.prototype.addKnown = function addKnown(host, key) {
}
this.known.set(host, key);
};
}
/**
* Add an authorized peer.
* @param {Buffer} key - Identity Key
*/
AuthDB.prototype.addAuthorized = function addAuthorized(key) {
addAuthorized(key) {
assert(Buffer.isBuffer(key) && key.length === 33,
'Invalid public key for authorized peer.');
this.authorized.push(key);
};
}
/**
* Initialize known peers with a host->key map.
* @param {Object} map
*/
AuthDB.prototype.setKnown = function setKnown(map) {
setKnown(map) {
this.known.clear();
for (const host of Object.keys(map)) {
const key = map[host];
this.addKnown(host, key);
}
};
}
/**
* Initialize authorized peers with a list of keys.
* @param {Buffer[]} keys
*/
AuthDB.prototype.setAuthorized = function setAuthorized(keys) {
setAuthorized(keys) {
this.authorized.length = 0;
for (const key of keys)
this.addAuthorized(key);
};
}
/**
* Get a known peer key by hostname.
@ -595,7 +600,7 @@ AuthDB.prototype.setAuthorized = function setAuthorized(keys) {
* @returns {Buffer|null}
*/
AuthDB.prototype.getKnown = function getKnown(hostname) {
getKnown(hostname) {
const known = this.known.get(hostname);
if (known)
@ -604,7 +609,7 @@ AuthDB.prototype.getKnown = function getKnown(hostname) {
const addr = IP.fromHostname(hostname);
return this.known.get(addr.host);
};
}
/**
* Lookup known peers.
@ -612,14 +617,14 @@ AuthDB.prototype.getKnown = function getKnown(hostname) {
* @returns {Promise}
*/
AuthDB.prototype.lookup = async function lookup() {
async lookup() {
const jobs = [];
for (const [addr, key] of this.dnsKnown)
jobs.push(this.populate(addr, key));
await Promise.all(jobs);
};
}
/**
* Populate known peers with hosts.
@ -630,7 +635,7 @@ AuthDB.prototype.lookup = async function lookup() {
* @returns {Promise}
*/
AuthDB.prototype.populate = async function populate(addr, key) {
async populate(addr, key) {
assert(addr.type === IP.types.DNS, 'Resolved host passed.');
this.logger.info('Resolving authorized hosts from: %s.', addr.host);
@ -649,7 +654,7 @@ AuthDB.prototype.populate = async function populate(addr, key) {
this.known.set(host, key);
}
};
}
/**
* Parse known peers.
@ -657,7 +662,7 @@ AuthDB.prototype.populate = async function populate(addr, key) {
* @returns {Object}
*/
AuthDB.prototype.readKnown = async function readKnown() {
async readKnown() {
if (fs.unsupported)
return;
@ -676,7 +681,7 @@ AuthDB.prototype.readKnown = async function readKnown() {
}
this.parseKnown(text);
};
}
/**
* Parse known peers.
@ -684,7 +689,7 @@ AuthDB.prototype.readKnown = async function readKnown() {
* @returns {Object}
*/
AuthDB.prototype.parseKnown = function parseKnown(text) {
parseKnown(text) {
assert(typeof text === 'string');
if (text.charCodeAt(0) === 0xfeff)
@ -735,7 +740,7 @@ AuthDB.prototype.parseKnown = function parseKnown(text) {
this.addKnown(addr, key);
}
};
}
/**
* Parse known peers.
@ -743,7 +748,7 @@ AuthDB.prototype.parseKnown = function parseKnown(text) {
* @returns {Object}
*/
AuthDB.prototype.readAuth = async function readAuth() {
async readAuth() {
if (fs.unsupported)
return;
@ -762,7 +767,7 @@ AuthDB.prototype.readAuth = async function readAuth() {
}
this.parseAuth(text);
};
}
/**
* Parse authorized peers.
@ -770,7 +775,7 @@ AuthDB.prototype.readAuth = async function readAuth() {
* @returns {Buffer[]} keys
*/
AuthDB.prototype.parseAuth = function parseAuth(text) {
parseAuth(text) {
assert(typeof text === 'string');
if (text.charCodeAt(0) === 0xfeff)
@ -799,7 +804,8 @@ AuthDB.prototype.parseAuth = function parseAuth(text) {
this.addAuthorized(key);
}
};
}
}
/*
* Expose

View File

@ -39,10 +39,9 @@ const INFO_SID = Buffer.from('BitcoinSessionID', 'ascii');
const HIGH_WATERMARK = 1024 * (1 << 20);
/**
* BIP151 Stream
* Represents a BIP151 input or output stream.
* @alias module:net.BIP151Stream
* @constructor
* @param {Number} cipher
* @property {Buffer} publicKey
* @property {Buffer} privateKey
* @property {Number} cipher
@ -57,10 +56,14 @@ const HIGH_WATERMARK = 1024 * (1 << 20);
* @property {Number} lastKey
*/
function BIP151Stream(cipher) {
if (!(this instanceof BIP151Stream))
return new BIP151Stream(cipher);
class BIP151Stream {
/**
* Create a BIP151 input or output stream.
* @constructor
* @param {Number} cipher
*/
constructor(cipher) {
this.cipher = BIP151.ciphers.CHACHAPOLY;
this.privateKey = secp256k1.generatePrivateKey();
this.publicKey = null;
@ -90,7 +93,7 @@ function BIP151Stream(cipher) {
* @param {Buffer} publicKey
*/
BIP151Stream.prototype.init = function init(publicKey) {
init(publicKey) {
assert(Buffer.isBuffer(publicKey));
this.publicKey = publicKey;
@ -117,7 +120,7 @@ BIP151Stream.prototype.init = function init(publicKey) {
this.aead.init(this.k2, this.iv);
this.lastRekey = util.now();
};
}
/**
* Add buffer size to `processed`,
@ -126,7 +129,7 @@ BIP151Stream.prototype.init = function init(publicKey) {
* @returns {Boolean}
*/
BIP151Stream.prototype.shouldRekey = function shouldRekey(packet) {
shouldRekey(packet) {
const now = util.now();
this.processed += packet.length;
@ -139,14 +142,14 @@ BIP151Stream.prototype.shouldRekey = function shouldRekey(packet) {
}
return false;
};
}
/**
* Generate new chacha keys with `key = HASH256(sid | key)`.
* This will reinitialize the state of both ciphers.
*/
BIP151Stream.prototype.rekey = function rekey(k1, k2) {
rekey(k1, k2) {
assert(this.sid, 'Cannot rekey before initialization.');
if (!k1) {
@ -164,7 +167,7 @@ BIP151Stream.prototype.rekey = function rekey(k1, k2) {
// aside from the sequence number.
this.chacha.init(this.k1, this.iv);
this.aead.init(this.k2, this.iv);
};
}
/**
* Increment packet sequence number and update IVs
@ -173,7 +176,7 @@ BIP151Stream.prototype.rekey = function rekey(k1, k2) {
* cipher state.
*/
BIP151Stream.prototype.sequence = function sequence() {
sequence() {
// Wrap sequence number a la openssh.
if (++this.seq === 0x100000000)
this.seq = 0;
@ -184,17 +187,17 @@ BIP151Stream.prototype.sequence = function sequence() {
// unaltered aside from the iv.
this.chacha.init(null, this.iv);
this.aead.init(null, this.iv);
};
}
/**
* Render the IV necessary for cipher streams.
* @returns {Buffer}
*/
BIP151Stream.prototype.update = function update() {
update() {
this.iv.writeUInt32LE(this.seq, 0, true);
return this.iv;
};
}
/**
* Get public key tied to private key
@ -202,9 +205,9 @@ BIP151Stream.prototype.update = function update() {
* @returns {Buffer}
*/
BIP151Stream.prototype.getPublicKey = function getPublicKey() {
getPublicKey() {
return secp256k1.publicKeyCreate(this.privateKey, true);
};
}
/**
* Encrypt a payload size with k1.
@ -212,9 +215,9 @@ BIP151Stream.prototype.getPublicKey = function getPublicKey() {
* @returns {Buffer}
*/
BIP151Stream.prototype.encryptSize = function encryptSize(data) {
encryptSize(data) {
return this.chacha.encrypt(data.slice(0, 4));
};
}
/**
* Decrypt payload size with k1.
@ -222,10 +225,10 @@ BIP151Stream.prototype.encryptSize = function encryptSize(data) {
* @returns {Number}
*/
BIP151Stream.prototype.decryptSize = function decryptSize(data) {
decryptSize(data) {
this.chacha.encrypt(data);
return data.readUInt32LE(0, true);
};
}
/**
* Encrypt payload with AEAD (update cipher and mac).
@ -233,9 +236,9 @@ BIP151Stream.prototype.decryptSize = function decryptSize(data) {
* @returns {Buffer} data
*/
BIP151Stream.prototype.encrypt = function encrypt(data) {
encrypt(data) {
return this.aead.encrypt(data);
};
}
/**
* Decrypt payload with AEAD (update cipher only).
@ -243,9 +246,9 @@ BIP151Stream.prototype.encrypt = function encrypt(data) {
* @returns {Buffer} data
*/
BIP151Stream.prototype.decrypt = function decrypt(data) {
decrypt(data) {
return this.aead.chacha20.encrypt(data);
};
}
/**
* Authenticate payload with AEAD (update mac only).
@ -253,19 +256,19 @@ BIP151Stream.prototype.decrypt = function decrypt(data) {
* @returns {Buffer} data
*/
BIP151Stream.prototype.auth = function auth(data) {
auth(data) {
return this.aead.auth(data);
};
}
/**
* Finalize AEAD and compute MAC.
* @returns {Buffer}
*/
BIP151Stream.prototype.final = function final() {
final() {
this.tag = this.aead.final();
return this.tag;
};
}
/**
* Verify tag against mac in constant time.
@ -273,16 +276,17 @@ BIP151Stream.prototype.final = function final() {
* @returns {Boolean}
*/
BIP151Stream.prototype.verify = function verify(tag) {
verify(tag) {
return Poly1305.verify(this.tag, tag);
};
}
}
/**
* BIP151
* Represents a BIP151 input and output stream.
* Holds state for peer communication.
* @alias module:net.BIP151
* @constructor
* @param {Number} cipher
* @extends EventEmitter
* @property {BIP151Stream} input
* @property {BIP151Stream} output
* @property {Boolean} initReceived
@ -295,11 +299,15 @@ BIP151Stream.prototype.verify = function verify(tag) {
* @property {Boolean} handshake
*/
function BIP151(cipher) {
if (!(this instanceof BIP151))
return new BIP151(cipher);
class BIP151 extends EventEmitter {
/**
* Create a BIP151 input and output stream.
* @constructor
* @param {Number} cipher
*/
EventEmitter.call(this);
constructor(cipher) {
super();
this.input = new BIP151Stream(cipher);
this.output = new BIP151Stream(cipher);
@ -323,46 +331,27 @@ function BIP151(cipher) {
this.bip150 = null;
}
Object.setPrototypeOf(BIP151.prototype, EventEmitter.prototype);
/**
* Cipher list.
* @enum {Number}
*/
BIP151.ciphers = {
CHACHAPOLY: 0
};
/**
* Max message size.
* @const {Number}
* @default
*/
BIP151.MAX_MESSAGE = 12 * 1000 * 1000;
/**
* Emit an error.
* @param {...String} msg
*/
BIP151.prototype.error = function error() {
error() {
const msg = format.apply(null, arguments);
this.emit('error', new Error(msg));
};
}
/**
* Test whether handshake has completed.
* @returns {Boolean}
*/
BIP151.prototype.isReady = function isReady() {
isReady() {
return this.initSent
&& this.ackReceived
&& this.initReceived
&& this.ackSent;
};
}
/**
* Render an `encinit` packet. Contains the
@ -370,11 +359,11 @@ BIP151.prototype.isReady = function isReady() {
* @returns {Buffer}
*/
BIP151.prototype.toEncinit = function toEncinit() {
toEncinit() {
assert(!this.initSent, 'Cannot init twice.');
this.initSent = true;
return new EncinitPacket(this.input.getPublicKey(), this.input.cipher);
};
}
/**
* Render `encack` packet. Contains the
@ -382,7 +371,7 @@ BIP151.prototype.toEncinit = function toEncinit() {
* @returns {Buffer}
*/
BIP151.prototype.toEncack = function toEncack() {
toEncack() {
assert(this.output.sid, 'Cannot ack before init.');
assert(!this.ackSent, 'Cannot ack twice.');
this.ackSent = true;
@ -394,7 +383,7 @@ BIP151.prototype.toEncack = function toEncack() {
}
return new EncackPacket(this.output.getPublicKey());
};
}
/**
* Render `encack` packet with an all
@ -403,30 +392,30 @@ BIP151.prototype.toEncack = function toEncack() {
* @returns {Buffer}
*/
BIP151.prototype.toRekey = function toRekey() {
toRekey() {
assert(this.handshake, 'Cannot rekey before handshake.');
return new EncackPacket(encoding.ZERO_KEY);
};
}
/**
* Handle `encinit` from remote peer.
* @param {Buffer}
*/
BIP151.prototype.encinit = function encinit(publicKey, cipher) {
encinit(publicKey, cipher) {
assert(cipher === this.output.cipher, 'Cipher mismatch.');
assert(!this.initReceived, 'Already initialized.');
assert(!this.completed, 'No encinit after timeout.');
this.initReceived = true;
this.output.init(publicKey);
};
}
/**
* Handle `encack` from remote peer.
* @param {Buffer} data
*/
BIP151.prototype.encack = function encack(publicKey) {
encack(publicKey) {
assert(this.initSent, 'Unsolicited ACK.');
if (publicKey.equals(encoding.ZERO_KEY)) {
@ -452,14 +441,14 @@ BIP151.prototype.encack = function encack(publicKey) {
this.handshake = true;
this.emit('handshake');
}
};
}
/**
* Cleanup handshake job.
* @returns {Job}
*/
BIP151.prototype.cleanup = function cleanup() {
cleanup() {
const job = this.job;
assert(!this.completed, 'Already completed.');
@ -479,27 +468,27 @@ BIP151.prototype.cleanup = function cleanup() {
}
return job;
};
}
/**
* Complete the timeout for handshake.
* @param {Object} result
*/
BIP151.prototype.resolve = function resolve(result) {
resolve(result) {
const job = this.cleanup();
job.resolve(result);
};
}
/**
* Complete the timeout for handshake with error.
* @param {Error} err
*/
BIP151.prototype.reject = function reject(err) {
reject(err) {
const job = this.cleanup();
job.reject(err);
};
}
/**
* Set a timeout and wait for handshake to complete.
@ -507,11 +496,11 @@ BIP151.prototype.reject = function reject(err) {
* @returns {Promise}
*/
BIP151.prototype.wait = function wait(timeout) {
wait(timeout) {
return new Promise((resolve, reject) => {
this._wait(timeout, resolve, reject);
});
};
}
/**
* Set a timeout and wait for handshake to complete.
@ -521,7 +510,7 @@ BIP151.prototype.wait = function wait(timeout) {
* @param {Function} reject
*/
BIP151.prototype._wait = function _wait(timeout, resolve, reject) {
_wait(timeout, resolve, reject) {
assert(!this.handshake, 'Cannot wait for init after handshake.');
this.job = { resolve, reject };
@ -532,18 +521,18 @@ BIP151.prototype._wait = function _wait(timeout, resolve, reject) {
this.onShake = this.resolve.bind(this);
this.once('handshake', this.onShake);
};
}
/**
* Destroy BIP151 state and streams.
*/
BIP151.prototype.destroy = function destroy() {
destroy() {
if (!this.job)
return;
this.reject(new Error('BIP151 stream was destroyed.'));
};
}
/**
* Add buffer size to `processed`,
@ -551,7 +540,7 @@ BIP151.prototype.destroy = function destroy() {
* @param {Buffer} packet
*/
BIP151.prototype.maybeRekey = function maybeRekey(packet) {
maybeRekey(packet) {
if (!this.output.shouldRekey(packet))
return;
@ -563,7 +552,7 @@ BIP151.prototype.maybeRekey = function maybeRekey(packet) {
}
this.output.rekey();
};
}
/**
* Calculate packet size.
@ -572,7 +561,7 @@ BIP151.prototype.maybeRekey = function maybeRekey(packet) {
* @returns {Number}
*/
BIP151.prototype.packetSize = function packetSize(cmd, body) {
packetSize(cmd, body) {
let size = 0;
size += 4;
size += encoding.sizeVarString(cmd, 'ascii');
@ -580,7 +569,7 @@ BIP151.prototype.packetSize = function packetSize(cmd, body) {
size += body.length;
size += 16;
return size;
};
}
/**
* Frame plaintext payload for the output stream.
@ -589,7 +578,7 @@ BIP151.prototype.packetSize = function packetSize(cmd, body) {
* @returns {Buffer} Ciphertext payload
*/
BIP151.prototype.packet = function packet(cmd, body) {
packet(cmd, body) {
const size = this.packetSize(cmd, body);
const bw = bio.write(size);
const payloadSize = size - 20;
@ -611,7 +600,7 @@ BIP151.prototype.packet = function packet(cmd, body) {
this.output.sequence();
return msg;
};
}
/**
* Feed ciphertext payload chunk
@ -620,7 +609,7 @@ BIP151.prototype.packet = function packet(cmd, body) {
* @param {Buffer} data
*/
BIP151.prototype.feed = function feed(data) {
feed(data) {
this.total += data.length;
this.pending.push(data);
@ -628,7 +617,7 @@ BIP151.prototype.feed = function feed(data) {
const chunk = this.read(this.waiting);
this.parse(chunk);
}
};
}
/**
* Read and consume a number of bytes
@ -637,7 +626,7 @@ BIP151.prototype.feed = function feed(data) {
* @returns {Buffer}
*/
BIP151.prototype.read = function read(size) {
read(size) {
assert(this.total >= size, 'Reading too much.');
if (size === 0)
@ -676,7 +665,7 @@ BIP151.prototype.read = function read(size) {
this.total -= chunk.length;
return chunk;
};
}
/**
* Parse a ciphertext payload chunk.
@ -684,7 +673,7 @@ BIP151.prototype.read = function read(size) {
* @param {Buffer} data
*/
BIP151.prototype.parse = function parse(data) {
parse(data) {
if (!this.hasSize) {
const size = this.input.decryptSize(data);
@ -744,8 +733,26 @@ BIP151.prototype.parse = function parse(data) {
this.emit('packet', cmd, body);
}
}
}
/**
* Cipher list.
* @enum {Number}
*/
BIP151.ciphers = {
CHACHAPOLY: 0
};
/**
* Max message size.
* @const {Number}
* @default
*/
BIP151.MAX_MESSAGE = 12 * 1000 * 1000;
/*
* Expose
*/

View File

@ -12,16 +12,18 @@ const Network = require('../protocol/network');
const hash256 = require('bcrypto/lib/hash256');
/**
* Protocol packet framer
* Protocol Message Framer
* @alias module:net.Framer
*/
class Framer {
/**
* Create a framer.
* @constructor
* @param {Network} network
*/
function Framer(network) {
if (!(this instanceof Framer))
return new Framer(network);
constructor(network) {
this.network = Network.get(network);
}
@ -33,7 +35,7 @@ function Framer(network) {
* @returns {Buffer} Payload with header prepended.
*/
Framer.prototype.packet = function packet(cmd, payload, checksum) {
packet(cmd, payload, checksum) {
assert(payload, 'No payload.');
assert(cmd.length < 12);
assert(payload.length <= 0xffffffff);
@ -61,7 +63,8 @@ Framer.prototype.packet = function packet(cmd, payload, checksum) {
payload.copy(msg, 24);
return msg;
};
}
}
/*
* Expose

File diff suppressed because it is too large Load Diff

View File

@ -18,19 +18,22 @@ const common = require('./common');
const packets = require('./packets');
/**
* Protocol packet parser
* Protocol Message Parser
* @alias module:net.Parser
* @constructor
* @param {Network} network
* @extends EventEmitter
* @emits Parser#error
* @emits Parser#packet
*/
function Parser(network) {
if (!(this instanceof Parser))
return new Parser(network);
class Parser extends EventEmitter {
/**
* Create a parser.
* @constructor
* @param {Network} network
*/
EventEmitter.call(this);
constructor(network) {
super();
this.network = Network.get(network);
@ -40,25 +43,23 @@ function Parser(network) {
this.header = null;
}
Object.setPrototypeOf(Parser.prototype, EventEmitter.prototype);
/**
* Emit an error.
* @private
* @param {...String} msg
*/
Parser.prototype.error = function error() {
error() {
const msg = format.apply(null, arguments);
this.emit('error', new Error(msg));
};
}
/**
* Feed data to the parser.
* @param {Buffer} data
*/
Parser.prototype.feed = function feed(data) {
feed(data) {
this.total += data.length;
this.pending.push(data);
@ -80,14 +81,14 @@ Parser.prototype.feed = function feed(data) {
this.total -= chunk.length;
this.parse(chunk);
}
};
}
/**
* Parse a fully-buffered chunk.
* @param {Buffer} chunk
*/
Parser.prototype.parse = function parse(data) {
parse(data) {
assert(data.length <= common.MAX_MESSAGE);
if (!this.header) {
@ -119,7 +120,7 @@ Parser.prototype.parse = function parse(data) {
this.header = null;
this.emit('packet', payload);
};
}
/**
* Parse buffered packet header.
@ -127,7 +128,7 @@ Parser.prototype.parse = function parse(data) {
* @returns {Header}
*/
Parser.prototype.parseHeader = function parseHeader(data) {
parseHeader(data) {
const magic = data.readUInt32LE(0, true);
if (magic !== this.network.magic) {
@ -159,7 +160,7 @@ Parser.prototype.parseHeader = function parseHeader(data) {
const checksum = data.readUInt32LE(20, true);
return new Header(cmd, size, checksum);
};
}
/**
* Parse a payload.
@ -168,21 +169,28 @@ Parser.prototype.parseHeader = function parseHeader(data) {
* @returns {Object}
*/
Parser.prototype.parsePayload = function parsePayload(cmd, data) {
parsePayload(cmd, data) {
return packets.fromRaw(cmd, data);
};
}
}
/**
* Packet Header
* @constructor
* @ignore
*/
function Header(cmd, size, checksum) {
class Header {
/**
* Create a header.
* @constructor
*/
constructor(cmd, size, checksum) {
this.cmd = cmd;
this.size = size;
this.checksum = checksum;
}
}
/*
* Expose

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff