github.com/defanghe/fabric@v2.1.1+incompatible/bccsp/factory/factory.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package factory 8 9 import ( 10 "sync" 11 12 "github.com/hyperledger/fabric/bccsp" 13 "github.com/hyperledger/fabric/common/flogging" 14 "github.com/pkg/errors" 15 ) 16 17 var ( 18 defaultBCCSP bccsp.BCCSP // default BCCSP 19 factoriesInitOnce sync.Once // factories' Sync on Initialization 20 factoriesInitError error // Factories' Initialization Error 21 22 // when InitFactories has not been called yet (should only happen 23 // in test cases), use this BCCSP temporarily 24 bootBCCSP bccsp.BCCSP 25 bootBCCSPInitOnce sync.Once 26 27 logger = flogging.MustGetLogger("bccsp") 28 ) 29 30 // BCCSPFactory is used to get instances of the BCCSP interface. 31 // A Factory has name used to address it. 32 type BCCSPFactory interface { 33 34 // Name returns the name of this factory 35 Name() string 36 37 // Get returns an instance of BCCSP using opts. 38 Get(opts *FactoryOpts) (bccsp.BCCSP, error) 39 } 40 41 // GetDefault returns a non-ephemeral (long-term) BCCSP 42 func GetDefault() bccsp.BCCSP { 43 if defaultBCCSP == nil { 44 logger.Debug("Before using BCCSP, please call InitFactories(). Falling back to bootBCCSP.") 45 bootBCCSPInitOnce.Do(func() { 46 var err error 47 bootBCCSP, err = (&SWFactory{}).Get(GetDefaultOpts()) 48 if err != nil { 49 panic("BCCSP Internal error, failed initialization with GetDefaultOpts!") 50 } 51 }) 52 return bootBCCSP 53 } 54 return defaultBCCSP 55 } 56 57 func initBCCSP(f BCCSPFactory, config *FactoryOpts) (bccsp.BCCSP, error) { 58 csp, err := f.Get(config) 59 if err != nil { 60 return nil, errors.Errorf("Could not initialize BCCSP %s [%s]", f.Name(), err) 61 } 62 63 return csp, nil 64 }