github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/common/ccprovider/ccinfocache.go (about)

     1  /*
     2  Copyright hechain. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package ccprovider
    18  
    19  import (
    20  	"fmt"
    21  	"sync"
    22  )
    23  
    24  // ccInfoCacheImpl implements in-memory cache for ChaincodeData
    25  // needed by endorser to verify if the local instantiation policy
    26  // matches the instantiation policy on a channel before honoring
    27  // an invoke
    28  type ccInfoCacheImpl struct {
    29  	sync.RWMutex
    30  
    31  	cache        map[string]*ChaincodeData
    32  	cacheSupport CCCacheSupport
    33  }
    34  
    35  // NewCCInfoCache returns a new cache on top of the supplied CCInfoProvider instance
    36  func NewCCInfoCache(cs CCCacheSupport) *ccInfoCacheImpl {
    37  	return &ccInfoCacheImpl{
    38  		cache:        make(map[string]*ChaincodeData),
    39  		cacheSupport: cs,
    40  	}
    41  }
    42  
    43  func (c *ccInfoCacheImpl) GetChaincodeData(ccNameVersion string) (*ChaincodeData, error) {
    44  	// c.cache is guaranteed to be non-nil
    45  
    46  	c.RLock()
    47  	ccdata, in := c.cache[ccNameVersion]
    48  	c.RUnlock()
    49  
    50  	if !in {
    51  		var err error
    52  
    53  		// the chaincode data is not in the cache
    54  		// try to look it up from the file system
    55  		ccpack, err := c.cacheSupport.GetChaincode(ccNameVersion)
    56  		if err != nil || ccpack == nil {
    57  			return nil, fmt.Errorf("cannot retrieve package for chaincode %ss, error %s", ccNameVersion, err)
    58  		}
    59  
    60  		// we have a non-nil ChaincodeData, put it in the cache
    61  		c.Lock()
    62  		ccdata = ccpack.GetChaincodeData()
    63  		c.cache[ccNameVersion] = ccdata
    64  		c.Unlock()
    65  	}
    66  
    67  	return ccdata, nil
    68  }