github.com/Hnampk/my-fabric@v0.0.0-20201028083322-75069da399c0/bccsp/sw/inmemoryks.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package sw
     8  
     9  import (
    10  	"encoding/hex"
    11  	"sync"
    12  
    13  	"github.com/hyperledger/fabric/bccsp"
    14  	"github.com/pkg/errors"
    15  )
    16  
    17  // NewInMemoryKeyStore instantiates an ephemeral in-memory keystore
    18  func NewInMemoryKeyStore() bccsp.KeyStore {
    19  	eks := &inmemoryKeyStore{}
    20  	eks.keys = make(map[string]bccsp.Key)
    21  	return eks
    22  }
    23  
    24  type inmemoryKeyStore struct {
    25  	// keys maps the hex-encoded SKI to keys
    26  	keys map[string]bccsp.Key
    27  	m    sync.RWMutex
    28  }
    29  
    30  // ReadOnly returns false - the key store is not read-only
    31  func (ks *inmemoryKeyStore) ReadOnly() bool {
    32  	return false
    33  }
    34  
    35  // GetKey returns a key object whose SKI is the one passed.
    36  func (ks *inmemoryKeyStore) GetKey(ski []byte) (bccsp.Key, error) {
    37  	if len(ski) == 0 {
    38  		return nil, errors.New("ski is nil or empty")
    39  	}
    40  
    41  	skiStr := hex.EncodeToString(ski)
    42  
    43  	ks.m.RLock()
    44  	defer ks.m.RUnlock()
    45  	if key, found := ks.keys[skiStr]; found {
    46  		return key, nil
    47  	}
    48  	return nil, errors.Errorf("no key found for ski %x", ski)
    49  }
    50  
    51  // StoreKey stores the key k in this KeyStore.
    52  func (ks *inmemoryKeyStore) StoreKey(k bccsp.Key) error {
    53  	if k == nil {
    54  		return errors.New("key is nil")
    55  	}
    56  
    57  	ski := hex.EncodeToString(k.SKI())
    58  
    59  	ks.m.Lock()
    60  	defer ks.m.Unlock()
    61  
    62  	if _, found := ks.keys[ski]; found {
    63  		return errors.Errorf("ski %x already exists in the keystore", k.SKI())
    64  	}
    65  	ks.keys[ski] = k
    66  
    67  	return nil
    68  }