feat: add compact protobuf format (#76)

* docs: document .createFromProtobuf and .marshal
* fix: lint
* test: verify .marshal() does it's job
This commit is contained in:
Maciej Krüger
2019-07-12 19:35:46 +02:00
committed by Jacob Heun
parent f50b2ac016
commit 76864184da
6 changed files with 88 additions and 3 deletions

View File

@ -8,6 +8,7 @@ const mh = require('multihashes')
const cryptoKeys = require('libp2p-crypto/src/keys')
const assert = require('assert')
const withIs = require('class-is')
const { PeerIdProto } = require('./proto')
class PeerId {
constructor (id, privKey, pubKey) {
@ -67,6 +68,15 @@ class PeerId {
}
}
// Return the protobuf version of the peer-id
marshal (excludePriv) {
return PeerIdProto.encode({
id: this.toBytes(),
pubKey: this.marshalPubKey(),
privKey: excludePriv ? null : this.marshalPrivKey()
})
}
toPrint () {
let pid = this.toB58String()
// All sha256 nodes start with Qm
@ -232,6 +242,49 @@ exports.createFromJSON = async (obj) => {
return new PeerIdWithIs(id, privKey, pub)
}
exports.createFromProtobuf = async (buf) => {
if (typeof buf === 'string') {
buf = Buffer.from(buf, 'hex')
}
let { id, privKey, pubKey } = PeerIdProto.decode(buf)
privKey = privKey ? await cryptoKeys.unmarshalPrivateKey(privKey) : false
pubKey = pubKey ? await cryptoKeys.unmarshalPublicKey(pubKey) : false
let pubDigest
let privDigest
if (privKey) {
privDigest = await computeDigest(privKey.public)
}
if (pubKey) {
pubDigest = await computeDigest(pubKey)
}
if (privKey) {
if (pubKey) {
if (!privDigest.equals(pubDigest)) {
throw new Error('Public and private key do not match')
}
}
return new PeerIdWithIs(privDigest, privKey, privKey.public)
}
// TODO: val id and pubDigest
if (pubKey) {
return new PeerIdWithIs(pubDigest, null, pubKey)
}
if (id) {
return new PeerIdWithIs(id)
}
throw new Error('Protobuf did not contain any usable key material')
}
exports.isPeerId = (peerId) => {
return Boolean(typeof peerId === 'object' &&
peerId._id &&

12
src/proto.js Normal file
View File

@ -0,0 +1,12 @@
'use strict'
const protons = require('protons')
module.exports = protons(`
message PeerIdProto {
required bytes id = 1;
bytes pubKey = 2;
bytes privKey = 3;
}
`)