Skip to content

Commit

Permalink
feat: Add compact protobuf format
Browse files Browse the repository at this point in the history
  • Loading branch information
mkg20001 committed Feb 16, 2018
1 parent 464c92a commit c979efb
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"async": "^2.6.0",
"libp2p-crypto": "~0.12.1",
"lodash": "^4.17.5",
"multihashes": "~0.4.13"
"multihashes": "~0.4.13",
"protons": "^1.0.1"
},
"repository": {
"type": "git",
Expand Down
68 changes: 68 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ const crypto = require('libp2p-crypto')
const assert = require('assert')
const waterfall = require('async/waterfall')

const protons = require('protons')
const {PeerIdProto} = protons('message PeerIdProto { required bytes id = 1; bytes pubKey = 2; bytes privKey = 3; }')

class PeerId {
constructor (id, privKey, pubKey) {
assert(Buffer.isBuffer(id), 'invalid id provided')
Expand Down Expand Up @@ -67,6 +70,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()
})
}

// pretty print
toPrint () {
return this.toJSON()
Expand Down Expand Up @@ -221,6 +233,62 @@ exports.createFromPrivKey = function (key, callback) {
})
}

exports.createFromProtobuf = function (buf, callback) {
if (typeof callback !== 'function') {
throw new Error('callback is required')
}

let obj
let id
let rawPrivKey
let rawPubKey
let pub

try {
obj = PeerIdProto.decode(buf)
id = obj.id
rawPrivKey = obj.privKey
rawPubKey = obj.pubKey
pub = rawPubKey && crypto.keys.unmarshalPublicKey(rawPubKey)
} catch (err) {
return callback(err)
}

if (rawPrivKey) {
waterfall([
(cb) => crypto.keys.unmarshalPrivateKey(rawPrivKey, cb),
(priv, cb) => priv.public.hash((err, digest) => {
cb(err, digest, priv)
}),
(privDigest, priv, cb) => {
if (pub) {
pub.hash((err, pubDigest) => {
cb(err, privDigest, priv, pubDigest)
})
} else {
cb(null, privDigest, priv)
}
}
], (err, privDigest, priv, pubDigest) => {
if (err) {
return callback(err)
}

if (pub && !privDigest.equals(pubDigest)) {
return callback(new Error('Public and private key do not match'))
}

if (id && !privDigest.equals(id)) {
return callback(new Error('Id and private key do not match'))
}

callback(null, new PeerId(id, priv, pub))
})
} else {
callback(null, new PeerId(id, null, pub))
}
}

exports.createFromJSON = function (obj, callback) {
if (typeof callback !== 'function') {
throw new Error('callback is required')
Expand Down

0 comments on commit c979efb

Please sign in to comment.