Skip to content

Commit

Permalink
[FAB-3423] Remove unsafe type assertions in config.go
Browse files Browse the repository at this point in the history
Change-Id: I2a5fac0759e1800182ebe06af06b57ceea4da930
Signed-off-by: Divyank Katira <[email protected]>
  • Loading branch information
d1vyank committed Apr 26, 2017
1 parent ec9d2ef commit dbdac6e
Show file tree
Hide file tree
Showing 9 changed files with 69 additions and 93 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
*.db
*report.xml
.DS_Store
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
# Hyperledger Fabric Client SDK for Go
[![Build Status](https://jenkins.hyperledger.org/buildStatus/icon?job=fabric-sdk-go-tests-verify-x86_64)](https://jenkins.hyperledger.org/job/fabric-sdk-go-tests-verify-x86_64)
[![Build Status](https://jenkins.hyperledger.org/buildStatus/icon?job=fabric-sdk-go-tests-merge-x86_64)](https://jenkins.hyperledger.org/job/fabric-sdk-go-tests-merge-x86_64)
[![Go Report Card](https://goreportcard.com/badge/github.com/hyperledger/fabric-sdk-go)](https://goreportcard.com/report/github.com/hyperledger/fabric-sdk-go)
[![GoDoc](https://godoc.org/github.com/hyperledger/fabric-sdk-go?status.svg)](https://godoc.org/github.com/hyperledger/fabric-sdk-go)

The Hyperledger Fabric Client SDK makes it easy to use APIs to interact with a Hyperledger Fabric blockchain.

This SDK is targeted both towards the external access to a Hyperledger Fabric blockchain using a Go application, as well as being targeted at the internal library in a peer to access API functions on other parts of the network.

**NOTE:** In an effort to make the codebase more modular, there will be interface changes over the course of the next week.

This is a **read-only mirror** of the formal [Gerrit](https://gerrit.hyperledger.org/r/#/admin/projects/fabric-sdk-go)
repository, where active development is ongoing. Issue tracking is handled in [Jira](https://jira.hyperledger.org/secure/RapidBoard.jspa?projectKey=FAB&rapidView=7&view=planning)

Expand Down Expand Up @@ -50,4 +48,3 @@ go test
This client was last tested and found to be compatible with the following Hyperledger Fabric commit levels:
- fabric: v1.0.0-alpha
- fabric-ca: v1.0.0-alpha

80 changes: 25 additions & 55 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,17 @@ import (
"github.com/spf13/viper"
)

// PeerConfig ...
// PeerConfig A set of configurations required to connect to a Fabric peer
type PeerConfig struct {
Host string
Port string
EventHost string
EventPort string
TLSCertificate string
TLSServerHostOverride string
Primary bool
Host string
Port int
EventHost string
EventPort int
Primary bool
TLS struct {
Certificate string
ServerHostOverride string
}
}

var myViper = viper.New()
Expand Down Expand Up @@ -121,59 +123,27 @@ func GetFabricClientViper() *viper.Viper {
return myViper
}

// GetPeersConfig ...
func GetPeersConfig() []PeerConfig {
// GetPeersConfig Retrieves the fabric peers from the config file provided
func GetPeersConfig() ([]PeerConfig, error) {
peersConfig := []PeerConfig{}
peers := myViper.GetStringMap("client.peers")
for key, value := range peers {
mm, ok := value.(map[string]interface{})
var host string
var port int
var primary bool
var eventHost string
var eventPort int
var tlsCertificate string
var tlsServerHostOverride string

if ok {
host, _ = mm["host"].(string)
port, _ = mm["port"].(int)
primary, _ = mm["primary"].(bool)
eventHost, _ = mm["event_host"].(string)
eventPort, _ = mm["event_port"].(int)
tlsCertificate, _ = mm["tls"].(map[string]interface{})["certificate"].(string)
tlsServerHostOverride, _ = mm["tls"].(map[string]interface{})["serverhostoverride"].(string)

} else {
mm1 := value.(map[interface{}]interface{})
host, _ = mm1["host"].(string)
port, _ = mm1["port"].(int)
primary, _ = mm1["primary"].(bool)
eventHost, _ = mm1["event_host"].(string)
eventPort, _ = mm1["event_port"].(int)
tlsCertificate, _ = mm1["tls"].(map[string]interface{})["certificate"].(string)
tlsServerHostOverride, _ = mm1["tls"].(map[string]interface{})["serverhostoverride"].(string)

}

p := PeerConfig{Host: host, Port: strconv.Itoa(port), EventHost: eventHost, EventPort: strconv.Itoa(eventPort),
TLSCertificate: tlsCertificate, TLSServerHostOverride: tlsServerHostOverride, Primary: primary}
err := myViper.UnmarshalKey("client.peers", &peersConfig)
if err != nil {
return nil, err
}
for index, p := range peersConfig {
if p.Host == "" {
panic(fmt.Sprintf("host key not exist or empty for %s", key))
return nil, fmt.Errorf("host key not exist or empty for peer %d", index)
}
if p.Port == "" {
panic(fmt.Sprintf("port key not exist or empty for %s", key))
if p.Port == 0 {
return nil, fmt.Errorf("port key not exist or empty for peer %d", index)
}

if IsTLSEnabled() && p.TLSCertificate == "" {
panic(fmt.Sprintf("tls.certificate not exist or empty for %s", key))
if IsTLSEnabled() && p.TLS.Certificate == "" {
return nil, fmt.Errorf("tls.certificate not exist or empty for peer %d", index)
}

p.TLSCertificate = strings.Replace(p.TLSCertificate, "$GOPATH", os.Getenv("GOPATH"), -1)
peersConfig = append(peersConfig, p)
peersConfig[index].TLS.Certificate = strings.Replace(p.TLS.Certificate, "$GOPATH",
os.Getenv("GOPATH"), -1)
}
return peersConfig

return peersConfig, nil
}

// IsTLSEnabled ...
Expand Down
15 changes: 9 additions & 6 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,22 @@ import (
)

func TestGetPeersConfig(t *testing.T) {
pc := GetPeersConfig()
pc, err := GetPeersConfig()
if err != nil {
t.Fatalf(err.Error())
}

for _, value := range pc {
if value.Host == "" {
t.Fatalf("Host value is empty")
}
if value.Port == "" {
if value.Port == 0 {
t.Fatalf("Port value is empty")
}
if value.Port == "" {
if value.EventHost == "" {
t.Fatalf("EventHost value is empty")
}
if value.Port == "" {
if value.EventPort == 0 {
t.Fatalf("EventPort value is empty")
}

Expand Down Expand Up @@ -72,8 +75,8 @@ func TestMultipleVipers(t *testing.T) {
t.Fatalf("Expected testvalue after config initialization")
}
// Make sure Go SDK config is unaffected
testValue3 := myViper.GetString("client.peers.peer1.host")
if testValue3 != "localhost" {
testValue3 := myViper.GetBool("client.tls.enabled")
if testValue3 != true {
t.Fatalf("Expected existing config value to remain unchanged")
}
}
Expand Down
13 changes: 3 additions & 10 deletions fabric-client/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -1318,17 +1318,10 @@ func (c *chain) fetchGenesisBlock() (*common.Block, error) {
return nil, fmt.Errorf("Error signing payload: %s", err)
}
// Request genesis block from ordering service
var block *common.Block
// TODO: what if the primary orderer is down?
responses, errors := c.GetOrderers()[0].SendDeliver(blockRequest)
// Block on channels for genesis block or error
select {
case block = <-responses:
logger.Debugf("Got genesis block from ordering service: %#v", block)
case err = <-errors:
return nil, fmt.Errorf("Error from SendDeliver(): %s", err)
block, err := c.SendEnvelope(blockRequest)
if err != nil {
return nil, fmt.Errorf("Error from SendEnvelope: %s", err.Error())
}

return block, nil
}

Expand Down
11 changes: 8 additions & 3 deletions fabric-client/helpers/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,13 @@ func GetChain(client fabricClient.Client, chainID string) (fabricClient.Chain, e
}
chain.AddOrderer(orderer)

for _, p := range config.GetPeersConfig() {
endorser, err := fabricClient.NewPeer(fmt.Sprintf("%s:%s", p.Host, p.Port), p.TLSCertificate, p.TLSServerHostOverride)
peerConfig, err := config.GetPeersConfig()
if err != nil {
return nil, fmt.Errorf("Error reading peer config: %v", err)
}
for _, p := range peerConfig {
endorser, err := fabricClient.NewPeer(fmt.Sprintf("%s:%d", p.Host, p.Port),
p.TLS.Certificate, p.TLS.ServerHostOverride)
if err != nil {
return nil, fmt.Errorf("NewPeer return error: %v", err)
}
Expand Down Expand Up @@ -164,7 +169,7 @@ func CreateAndJoinChannel(client fabricClient.Client, chain fabricClient.Chain,
// Wait for orderer to process channel metadata
time.Sleep(time.Second * 2)
// Test join channel
creator, err := getCreatorID(client)
creator, err := GetCreatorID(client)
if err != nil {
return fmt.Errorf("Could not generate creator ID: %v", err)
}
Expand Down
8 changes: 4 additions & 4 deletions fabric-client/helpers/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func GetClient(name string, pwd string, stateStorePath string) (fabricClient.Cli
if user == nil {
fabricCAClient, err1 := fabricCAClient.NewFabricCAClient()
if err1 != nil {
return nil, fmt.Errorf("NewFabricCAClient return error: %v", err)
return nil, fmt.Errorf("NewFabricCAClient return error: %v", err1)
}
key, cert, err1 := fabricCAClient.Enroll(name, pwd)
keyPem, _ := pem.Decode(key)
Expand All @@ -111,7 +111,7 @@ func GetClient(name string, pwd string, stateStorePath string) (fabricClient.Cli
user := fabricClient.NewUser(name)
k, err1 := client.GetCryptoSuite().KeyImport(keyPem.Bytes, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: false})
if err1 != nil {
return nil, fmt.Errorf("KeyImport return error: %v", err)
return nil, fmt.Errorf("KeyImport return error: %v", err1)
}
user.SetPrivateKey(k)
user.SetEnrollmentCertificate(cert)
Expand All @@ -125,8 +125,8 @@ func GetClient(name string, pwd string, stateStorePath string) (fabricClient.Cli

}

// Utility method gets serialized enrollment certificate
func getCreatorID(client fabricClient.Client) ([]byte, error) {
// GetCreatorID gets serialized enrollment certificate
func GetCreatorID(client fabricClient.Client) ([]byte, error) {

user, err := client.LoadUserFromStateStore("")
if err != nil {
Expand Down
15 changes: 8 additions & 7 deletions test/fixtures/config/config_test.yaml
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
client:
peers:
peer1:
host: "localhost"
# peer0
- host: "localhost"
port: 7051
event_host: "localhost"
event_port: 7053
eventHost: "localhost"
eventPort: 7053
primary: true
tls:
# Certificate location absolute path
certificate: "$GOPATH/src/github.com/hyperledger/fabric-sdk-go/test/fixtures/tls/peers/peer0/ca-cert.pem"
serverHostOverride: "peer0"

peer2:
host: "localhost"
# peer 1
- host: "localhost"
port: 7056
eventHost: "localhost"
eventPort: 7058
primary: false
tls:
# Certificate location absolute path
Expand Down
13 changes: 9 additions & 4 deletions test/integration/base_test_setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,15 @@ func (setup *BaseSetupImpl) MoveFunds() (string, error) {
func getEventHub() (events.EventHub, error) {
eventHub := events.NewEventHub()
foundEventHub := false
for _, p := range config.GetPeersConfig() {
if p.EventHost != "" && p.EventPort != "" {
fmt.Printf("******* EventHub connect to peer (%s:%s) *******\n", p.EventHost, p.EventPort)
eventHub.SetPeerAddr(fmt.Sprintf("%s:%s", p.EventHost, p.EventPort), p.TLSCertificate, p.TLSServerHostOverride)
peerConfig, err := config.GetPeersConfig()
if err != nil {
return nil, fmt.Errorf("Error reading peer config: %v", err)
}
for _, p := range peerConfig {
if p.EventHost != "" && p.EventPort != 0 {
fmt.Printf("******* EventHub connect to peer (%s:%d) *******\n", p.EventHost, p.EventPort)
eventHub.SetPeerAddr(fmt.Sprintf("%s:%d", p.EventHost, p.EventPort),
p.TLS.Certificate, p.TLS.ServerHostOverride)
foundEventHub = true
break
}
Expand Down

0 comments on commit dbdac6e

Please sign in to comment.