diff --git a/package.json b/package.json index eb51be3..43d2dea 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "license": "MIT", "dependencies": { "async": "^2.6.1", + "bs58": "^4.0.1", "multihashing-async": "~0.5.1", "nodeify": "^1.0.1", "safe-buffer": "^5.1.2", diff --git a/src/index.js b/src/index.js index c3bb1d6..727a0e3 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,6 @@ 'use strict' +const bs58 = require('bs58') const multihashing = require('multihashing-async') module.exports = (keysProtobuf, randomBytes, crypto) => { @@ -73,6 +74,25 @@ module.exports = (keysProtobuf, randomBytes, crypto) => { ensure(callback) multihashing(this.bytes, 'sha2-256', callback) } + + /** + * Gets the ID of the key. + * + * The key id is the base58 encoding of the SHA-256 multihash of its public key. + * The public key is a protobuf encoding containing a type and the DER encoding + * of the PKCS SubjectPublicKeyInfo. + * + * @param {function(Error, id)} callback + * @returns {undefined} + */ + id (callback) { + this.public.hash((err, hash) => { + if (err) { + return callback(err) + } + callback(null, bs58.encode(hash)) + }) + } } function unmarshalSecp256k1PrivateKey (bytes, callback) { diff --git a/test/secp256k1.spec.js b/test/secp256k1.spec.js index 85d250d..7ce0780 100644 --- a/test/secp256k1.spec.js +++ b/test/secp256k1.spec.js @@ -85,6 +85,15 @@ describe('secp256k1 keys', () => { }) }) + it('key id', (done) => { + key.id((err, id) => { + expect(err).to.not.exist() + expect(id).to.exist() + expect(id).to.be.a('string') + done() + }) + }) + describe('key equals', () => { it('equals itself', () => { expect(key.equals(key)).to.eql(true)