keybook.go 1.75 KB
Newer Older
1
package pstoremem
Raúl Kripalani's avatar
Raúl Kripalani committed
2 3 4 5 6

import (
	"errors"
	"sync"

tavit ohanian's avatar
tavit ohanian committed
7 8
	ic "gitlab.dms3.io/p2p/go-p2p-core/crypto"
	peer "gitlab.dms3.io/p2p/go-p2p-core/peer"
Raúl Kripalani's avatar
Raúl Kripalani committed
9

tavit ohanian's avatar
tavit ohanian committed
10
	pstore "gitlab.dms3.io/p2p/go-p2p-core/peerstore"
Raúl Kripalani's avatar
Raúl Kripalani committed
11 12 13 14 15 16 17 18
)

type memoryKeyBook struct {
	sync.RWMutex // same lock. wont happen a ton.
	pks          map[peer.ID]ic.PubKey
	sks          map[peer.ID]ic.PrivKey
}

19
var _ pstore.KeyBook = (*memoryKeyBook)(nil)
Raúl Kripalani's avatar
Raúl Kripalani committed
20 21

// noop new, but in the future we may want to do some init work.
Yusef Napora's avatar
Yusef Napora committed
22
func NewKeyBook() *memoryKeyBook {
Raúl Kripalani's avatar
Raúl Kripalani committed
23 24 25 26 27 28
	return &memoryKeyBook{
		pks: map[peer.ID]ic.PubKey{},
		sks: map[peer.ID]ic.PrivKey{},
	}
}

29
func (mkb *memoryKeyBook) PeersWithKeys() peer.IDSlice {
Raúl Kripalani's avatar
Raúl Kripalani committed
30
	mkb.RLock()
31
	ps := make(peer.IDSlice, 0, len(mkb.pks)+len(mkb.sks))
Raúl Kripalani's avatar
Raúl Kripalani committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
	for p := range mkb.pks {
		ps = append(ps, p)
	}
	for p := range mkb.sks {
		if _, found := mkb.pks[p]; !found {
			ps = append(ps, p)
		}
	}
	mkb.RUnlock()
	return ps
}

func (mkb *memoryKeyBook) PubKey(p peer.ID) ic.PubKey {
	mkb.RLock()
	pk := mkb.pks[p]
	mkb.RUnlock()
	if pk != nil {
		return pk
	}
	pk, err := p.ExtractPublicKey()
52
	if err == nil {
Raúl Kripalani's avatar
Raúl Kripalani committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
		mkb.Lock()
		mkb.pks[p] = pk
		mkb.Unlock()
	}
	return pk
}

func (mkb *memoryKeyBook) AddPubKey(p peer.ID, pk ic.PubKey) error {
	// check it's correct first
	if !p.MatchesPublicKey(pk) {
		return errors.New("ID does not match PublicKey")
	}

	mkb.Lock()
	mkb.pks[p] = pk
	mkb.Unlock()
	return nil
}

func (mkb *memoryKeyBook) PrivKey(p peer.ID) ic.PrivKey {
	mkb.RLock()
	sk := mkb.sks[p]
	mkb.RUnlock()
	return sk
}

func (mkb *memoryKeyBook) AddPrivKey(p peer.ID, sk ic.PrivKey) error {
	if sk == nil {
		return errors.New("sk is nil (PrivKey)")
	}

	// check it's correct first
	if !p.MatchesPrivateKey(sk) {
		return errors.New("ID does not match PrivateKey")
	}

	mkb.Lock()
	mkb.sks[p] = sk
	mkb.Unlock()
	return nil
}