From 8e813720dc3ec55f3aa9a25bee5f96f42acdc12c Mon Sep 17 00:00:00 2001 From: Justin Date: Thu, 11 May 2017 10:52:35 +0100 Subject: [PATCH] Add ExtractPublicKey function Also add ExtractEd25519PublicKey helper function --- peer.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/peer.go b/peer.go index a77fecd..ca29638 100644 --- a/peer.go +++ b/peer.go @@ -9,6 +9,7 @@ import ( logging "github.com/ipfs/go-log" // ID represents the identity of a peer. b58 "github.com/jbenet/go-base58" ic "github.com/libp2p/go-libp2p-crypto" + mc "github.com/multiformats/go-multicodec-packed" mh "github.com/multiformats/go-multihash" ) @@ -63,6 +64,64 @@ func (id ID) MatchesPublicKey(pk ic.PubKey) bool { return oid == id } +func (id ID) ExtractEd25519PublicKey() ic.PubKey { + // ed25519 pubkey identity format + // + // <0x00 ><0x22 ><0xed01 > + + var nilPubKey ic.PubKey + + // Decode multihash + decoded, err := mh.Decode([]byte(id)) + if err != nil { + return nilPubKey + } + + // Check ID multihash codec + if decoded.Code != mh.ID { + return nilPubKey + } + + // Check multihash length + if decoded.Length != 2+32 { + return nilPubKey + } + + // Split prefix + code, pubKeyBytes := mc.SplitPrefix(decoded.Digest) + + // Check ed25519 code + if code != mc.Ed25519Pub { + return nilPubKey + } + + // Unmarshall public key + pubKey, err := ic.UnmarshalEd25519PublicKey(pubKeyBytes) + if err != nil { + return nilPubKey + } + + return pubKey +} + +func (id ID) ExtractPublicKey() ic.PubKey { + var pk ic.PubKey + + // Try extract ed25519 pubkey + pk = id.ExtractEd25519PublicKey() + if pk != nil { + return pk + } + + // Try extract other type of pubkey + /*pk = id.Extract...PublicKey() + if pk != nil { + return pk + }*/ + + return pk +} + // IDFromString cast a string to ID type, and validate // the id to make sure it is a multihash. func IDFromString(s string) (ID, error) {