github.com/kaituanwang/hyperledger@v2.0.1+incompatible/bccsp/factory/factory.go (about) 1 /* 2 Copyright IBM Corp. 2016 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 factory 18 19 import ( 20 "sync" 21 22 "github.com/hyperledger/fabric/bccsp" 23 "github.com/hyperledger/fabric/common/flogging" 24 "github.com/pkg/errors" 25 ) 26 27 var ( 28 // Default BCCSP 29 DefaultBCCSP bccsp.BCCSP 30 31 // when InitFactories has not been called yet (should only happen 32 // in test cases), use this BCCSP temporarily 33 bootBCCSP bccsp.BCCSP 34 35 // BCCSP Factories 36 bccspMap map[string]bccsp.BCCSP 37 38 // factories' Sync on Initialization 39 factoriesInitOnce sync.Once 40 bootBCCSPInitOnce sync.Once 41 42 // Factories' Initialization Error 43 factoriesInitError error 44 45 logger = flogging.MustGetLogger("bccsp") 46 ) 47 48 // BCCSPFactory is used to get instances of the BCCSP interface. 49 // A Factory has name used to address it. 50 type BCCSPFactory interface { 51 52 // Name returns the name of this factory 53 Name() string 54 55 // Get returns an instance of BCCSP using opts. 56 Get(opts *FactoryOpts) (bccsp.BCCSP, error) 57 } 58 59 // GetDefault returns a non-ephemeral (long-term) BCCSP 60 func GetDefault() bccsp.BCCSP { 61 if DefaultBCCSP == nil { 62 logger.Debug("Before using BCCSP, please call InitFactories(). Falling back to bootBCCSP.") 63 bootBCCSPInitOnce.Do(func() { 64 var err error 65 f := &SWFactory{} 66 bootBCCSP, err = f.Get(&FactoryOpts{ 67 ProviderName: "SW", 68 SwOpts: &SwOpts{ 69 HashFamily: "SHA2", 70 SecLevel: 256, 71 72 Ephemeral: true, 73 }}) 74 if err != nil { 75 panic("BCCSP Internal error, failed initialization with GetDefaultOpts!") 76 } 77 }) 78 return bootBCCSP 79 } 80 return DefaultBCCSP 81 } 82 83 func initBCCSP(f BCCSPFactory, config *FactoryOpts) error { 84 csp, err := f.Get(config) 85 if err != nil { 86 return errors.Errorf("Could not initialize BCCSP %s [%s]", f.Name(), err) 87 } 88 89 logger.Debugf("Initialize BCCSP [%s]", f.Name()) 90 bccspMap[f.Name()] = csp 91 return nil 92 }