|
| 1 | +// +build !nopkcs11 |
| 2 | + |
| 3 | +/* |
| 4 | +Copyright IBM Corp. 2017 All Rights Reserved. |
| 5 | +
|
| 6 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +you may not use this file except in compliance with the License. |
| 8 | +You may obtain a copy of the License at |
| 9 | +
|
| 10 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +
|
| 12 | +Unless required by applicable law or agreed to in writing, software |
| 13 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +See the License for the specific language governing permissions and |
| 16 | +limitations under the License. |
| 17 | +*/ |
| 18 | +package factory |
| 19 | + |
| 20 | +import ( |
| 21 | + "fmt" |
| 22 | + |
| 23 | + "github.com/hyperledger/fabric/bccsp" |
| 24 | +) |
| 25 | + |
| 26 | +type FactoryOpts struct { |
| 27 | + ProviderName string `mapstructure:"default" json:"default" yaml:"Default"` |
| 28 | + SwOpts *SwOpts `mapstructure:"SW,omitempty" json:"SW,omitempty" yaml:"SwOpts"` |
| 29 | + Pkcs11Opts *PKCS11Opts `mapstructure:"PKCS11,omitempty" json:"PKCS11,omitempty" yaml:"PKCS11"` |
| 30 | +} |
| 31 | + |
| 32 | +// InitFactories must be called before using factory interfaces |
| 33 | +// It is acceptable to call with config = nil, in which case |
| 34 | +// some defaults will get used |
| 35 | +// Error is returned only if defaultBCCSP cannot be found |
| 36 | +func InitFactories(config *FactoryOpts) error { |
| 37 | + factoriesInitOnce.Do(func() { |
| 38 | + // Take some precautions on default opts |
| 39 | + if config == nil { |
| 40 | + config = &DefaultOpts |
| 41 | + } |
| 42 | + |
| 43 | + if config.ProviderName == "" { |
| 44 | + config.ProviderName = "SW" |
| 45 | + } |
| 46 | + |
| 47 | + if config.SwOpts == nil { |
| 48 | + config.SwOpts = DefaultOpts.SwOpts |
| 49 | + } |
| 50 | + |
| 51 | + // Initialize factories map |
| 52 | + bccspMap = make(map[string]bccsp.BCCSP) |
| 53 | + |
| 54 | + // Software-Based BCCSP |
| 55 | + if config.SwOpts != nil { |
| 56 | + f := &SWFactory{} |
| 57 | + err := initBCCSP(f, config) |
| 58 | + if err != nil { |
| 59 | + factoriesInitError = fmt.Errorf("[%s]", err) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // PKCS11-Based BCCSP |
| 64 | + if config.Pkcs11Opts != nil { |
| 65 | + f := &PKCS11Factory{} |
| 66 | + err := initBCCSP(f, config) |
| 67 | + if err != nil { |
| 68 | + factoriesInitError = fmt.Errorf("%s\n[%s]", factoriesInitError, err) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + var ok bool |
| 73 | + defaultBCCSP, ok = bccspMap[config.ProviderName] |
| 74 | + if !ok { |
| 75 | + factoriesInitError = fmt.Errorf("%s\nCould not find default `%s` BCCSP", factoriesInitError, config.ProviderName) |
| 76 | + } |
| 77 | + }) |
| 78 | + |
| 79 | + return factoriesInitError |
| 80 | +} |
0 commit comments