This repository has been archived by the owner on Mar 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
90 lines (84 loc) · 2.28 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const EventEmitter = require('events')
const Capability = require('primea-capability')
const crypto = require('node-webcrypto-shim')
const leb128 = require('leb128').unsigned
const Pipe = require('buffer-pipe')
/**
* This implements Messages for Primea
* @module primea-message
*/
module.exports = class Message extends EventEmitter {
/**
* @param {Object} opts
* @param {ArrayBuffer} opts.data - the payload of the message
* @param {Array<Object>} opts.caps - an array of capabilities to send in the message
*/
constructor (opts = {}) {
super()
const defaults = this.constructor.defaults
this._opts = Object.assign(defaults, opts)
Object.keys(this._opts).forEach(key => {
Object.defineProperty(this, key, {
get: function () {
return this._opts[key]
},
set: function (y) {
this._opts[key] = y
}
})
})
}
/**
* serializes the message
* @return {Buffer}
*/
serialize () {
const args = [
leb128.encode(this.ticks),
leb128.encode(this.data.length),
this.data,
Buffer.concat(this.caps.map(c => c.serialize()))
]
return Buffer.concat(args)
}
/**
* deserializes the message and returns a new instance of `Message`
* @param {Buffer} raw - the serialized raw message
* @return {Promise} resolve with a new instance of `Message`
*/
static deserialize (raw) {
const p = new Pipe(raw)
const json = {
ticks: leb128.readBn(p).toNumber(),
data: p.read(leb128.read(p))
}
json.caps = []
while (!p.end) {
const cap = Capability.deserializeFromPipe(p)
json.caps.push(cap)
}
return new Message(json)
}
/**
* Gets the SHA-256 hash for some given data
* @param {Buffer} data - the data to be hashed
* @param {number} length - the number of bytes of the hash to return. must be <= 32
* @returns {Promise} resolves with 32 bytes of hashed data
*/
static hash (data, length = 32) {
return crypto.subtle.digest({
name: 'SHA-256'
}, data).then(function (hash) {
return new Uint8Array(hash).subarray(0, length)
})
}
static get defaults () {
return {
ticks: 0,
data: new Uint8Array([]),
caps: [],
_fromId: Buffer.alloc(20),
_fromTicks: 0
}
}
}