mirror of
https://github.com/fluencelabs/js-peer-id
synced 2025-06-27 09:11:34 +00:00
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:
committed by
Jacob Heun
parent
f50b2ac016
commit
76864184da
53
src/index.js
53
src/index.js
@ -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
12
src/proto.js
Normal 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;
|
||||
}
|
||||
|
||||
`)
|
Reference in New Issue
Block a user