js-libp2p/test/record/envelope.spec.js

88 lines
2.5 KiB
JavaScript
Raw Normal View History

'use strict'
/* eslint-env mocha */
2021-04-27 17:13:34 +02:00
const { expect } = require('aegir/utils/chai')
2021-08-16 21:29:06 +02:00
const { fromString: uint8arrayFromString } = require('uint8arrays/from-string')
const { equals: uint8arrayEquals } = require('uint8arrays/equals')
2020-06-24 15:10:08 +02:00
const Envelope = require('../../src/record/envelope')
2020-06-26 17:37:53 +02:00
const { codes: ErrorCodes } = require('../../src/errors')
const peerUtils = require('../utils/creators/peer')
2020-06-26 17:37:53 +02:00
const domain = 'libp2p-testing'
const codec = uint8arrayFromString('/libp2p/testdata')
2020-12-10 14:48:14 +01:00
class TestRecord {
constructor (data) {
2020-12-10 14:48:14 +01:00
this.domain = domain
this.codec = codec
this.data = data
}
marshal () {
return uint8arrayFromString(this.data)
}
2020-07-15 11:40:57 +02:00
equals (other) {
return uint8arrayEquals(this.data, other.data)
}
}
describe('Envelope', () => {
const payloadType = codec
let peerId
let testRecord
before(async () => {
[peerId] = await peerUtils.createPeerId()
testRecord = new TestRecord('test-data')
})
it('creates an envelope with a random key', () => {
const payload = testRecord.marshal()
const signature = uint8arrayFromString(Math.random().toString(36).substring(7))
const envelope = new Envelope({
peerId,
payloadType,
payload,
signature
})
expect(envelope).to.exist()
expect(envelope.peerId.equals(peerId)).to.eql(true)
expect(envelope.payloadType).to.equalBytes(payloadType)
expect(envelope.payload).to.equalBytes(payload)
expect(envelope.signature).to.equalBytes(signature)
})
it('can seal a record', async () => {
const envelope = await Envelope.seal(testRecord, peerId)
expect(envelope).to.exist()
expect(envelope.peerId.equals(peerId)).to.eql(true)
expect(envelope.payloadType).to.eql(payloadType)
expect(envelope.payload).to.exist()
expect(envelope.signature).to.exist()
})
it('can open and verify a sealed record', async () => {
const envelope = await Envelope.seal(testRecord, peerId)
const rawEnvelope = envelope.marshal()
const unmarshalledEnvelope = await Envelope.openAndCertify(rawEnvelope, testRecord.domain)
expect(unmarshalledEnvelope).to.exist()
2020-07-15 11:40:57 +02:00
const equals = envelope.equals(unmarshalledEnvelope)
expect(equals).to.eql(true)
})
2020-06-26 17:37:53 +02:00
it('throw on open and verify when a different domain is used', async () => {
const envelope = await Envelope.seal(testRecord, peerId)
const rawEnvelope = envelope.marshal()
2020-06-26 17:37:53 +02:00
await expect(Envelope.openAndCertify(rawEnvelope, '/bad-domain'))
.to.eventually.be.rejected()
.and.to.have.property('code', ErrorCodes.ERR_SIGNATURE_NOT_VALID)
})
})