github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/hyperledger/fabric/bccsp/factory/pluginfactory.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  package factory
     7  
     8  import (
     9  	"errors"
    10  	"fmt"
    11  	"os"
    12  	"plugin"
    13  
    14  	"github.com/hellobchain/third_party/hyperledger/fabric/bccsp"
    15  )
    16  
    17  const (
    18  	// PluginFactoryName is the factory name for BCCSP plugins
    19  	PluginFactoryName = "PLUGIN"
    20  )
    21  
    22  // PluginOpts contains the options for the PluginFactory
    23  type PluginOpts struct {
    24  	// Path to plugin library
    25  	Library string
    26  	// Config map for the plugin library
    27  	Config map[string]interface{}
    28  }
    29  
    30  // PluginFactory is the factory for BCCSP plugins
    31  type PluginFactory struct{}
    32  
    33  // Name returns the name of this factory
    34  func (f *PluginFactory) Name() string {
    35  	return PluginFactoryName
    36  }
    37  
    38  // Get returns an instance of BCCSP using Opts.
    39  func (f *PluginFactory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {
    40  	// check for valid config
    41  	if config == nil || config.PluginOpts == nil {
    42  		return nil, errors.New("Invalid config. It must not be nil.")
    43  	}
    44  
    45  	// Library is required property
    46  	if config.PluginOpts.Library == "" {
    47  		return nil, errors.New("Invalid config: missing property 'Library'")
    48  	}
    49  
    50  	// make sure the library exists
    51  	if _, err := os.Stat(config.PluginOpts.Library); err != nil {
    52  		return nil, fmt.Errorf("Could not find library '%s' [%s]", config.PluginOpts.Library, err)
    53  	}
    54  
    55  	// attempt to load the library as a plugin
    56  	plug, err := plugin.Open(config.PluginOpts.Library)
    57  	if err != nil {
    58  		return nil, fmt.Errorf("Failed to load plugin '%s' [%s]", config.PluginOpts.Library, err)
    59  	}
    60  
    61  	// lookup the required symbol 'New'
    62  	sym, err := plug.Lookup("New")
    63  	if err != nil {
    64  		return nil, fmt.Errorf("Could not find required symbol 'CryptoServiceProvider' [%s]", err)
    65  	}
    66  
    67  	// check to make sure symbol New meets the required function signature
    68  	newConfig, ok := sym.(func(config map[string]interface{}) (bccsp.BCCSP, error))
    69  	if !ok {
    70  		return nil, fmt.Errorf("Plugin does not implement the required function signature for 'New'")
    71  	}
    72  
    73  	return newConfig(config.PluginOpts.Config)
    74  }