Skip to content

Commit

Permalink
[FAB-5604] Make channelID a required parameter
Browse files Browse the repository at this point in the history
Currently channelID is defaulted to 'testchainid' so the
user is not required to specify -C option, which is
misleading. This change set sets default value to
empty string and checks that channelID is specified
for all the peer commands that need it, display
error message if not specified.

Change-Id: I13badbd54b53c73cb25f297b522be2daadd43b5b
Signed-off-by: Anil Ambati <[email protected]>
  • Loading branch information
Anil Ambati authored and yacovm committed Nov 26, 2017
1 parent 704790d commit d203895
Show file tree
Hide file tree
Showing 15 changed files with 115 additions and 59 deletions.
29 changes: 11 additions & 18 deletions docs/source/chaincode4noah.rst
Original file line number Diff line number Diff line change
Expand Up @@ -325,30 +325,23 @@ Which shows output similar to the example below:
install Package the specified chaincode into a deployment spec and save it on the peer's path.
instantiate Deploy the specified chaincode to the network.
invoke Invoke the specified chaincode.
list Get the instantiated chaincodes on a channel or installed chaincodes on a peer.
package Package the specified chaincode into a deployment spec.
query Query using the specified chaincode.
signpackage Sign the specified chaincode package
upgrade Upgrade chaincode.
Flags:
--cafile string Path to file containing PEM-encoded trusted certificate(s) for the ordering endpoint
-C, --chainID string The chain on which this command should be executed (default "testchainid")
-c, --ctor string Constructor message for the chaincode in JSON format (default "{}")
-E, --escc string The name of the endorsement system chaincode to be used for this chaincode
-l, --lang string Language the chaincode is written in (default "golang")
-n, --name string Name of the chaincode
-o, --orderer string Ordering service endpoint
-p, --path string Path to chaincode
-P, --policy string The endorsement policy associated to this chaincode
-t, --tid string Name of a custom ID generation algorithm (hashing and decoding) e.g. sha256base64
--tls Use TLS when communicating with the orderer endpoint
-u, --username string Username for chaincode operations when security is enabled
-v, --version string Version of the chaincode specified in install/instantiate/upgrade commands
-V, --vscc string The name of the verification system chaincode to be used for this chaincode
Global Flags:
--logging-level string Default logging level and overrides, see core.yaml for full syntax
--test.coverprofile string Done (default "coverage.cov")
--cafile string Path to file containing PEM-encoded trusted certificate(s) for the ordering endpoint
-h, --help help for chaincode
-o, --orderer string Ordering service endpoint
--tls Use TLS when communicating with the orderer endpoint
--transient string Transient map of arguments in JSON encoding
Global Flags:
--logging-level string Default logging level and overrides, see core.yaml for full syntax
--test.coverprofile string Done (default "coverage.cov")
-v, --version
Use "peer chaincode [command] --help" for more information about a command.
Expand Down
5 changes: 2 additions & 3 deletions docs/source/peer-chaincode-devmode.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ during chaincode development phase for rapid code/build/run/debug cycle
turnaround.

To keep this a realistic “dev” environment, we are going to keep it “out
of the box” - with one exception: we create two channels instead of
using the default ``testchainid`` channel to show how the single running
instance can be accessed from multiple channels.
of the box” - with one exception: we create two channels to show how the
single running instance can be accessed from multiple channels.

- Note: Make sure peer is not using TLS when running in dev mode.

Expand Down
5 changes: 2 additions & 3 deletions peer/chaincode/chaincode.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"fmt"

"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric/peer/common"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand Down Expand Up @@ -59,7 +58,7 @@ var (
chaincodeQueryRaw bool
chaincodeQueryHex bool
customIDGenAlg string
chainID string
channelID string
chaincodeVersion string
policy string
escc string
Expand Down Expand Up @@ -101,7 +100,7 @@ func resetFlags() {
fmt.Sprint("Username for chaincode operations when security is enabled"))
flags.StringVarP(&customIDGenAlg, "tid", "t", common.UndefinedParamValue,
fmt.Sprint("Name of a custom ID generation algorithm (hashing and decoding) e.g. sha256base64"))
flags.StringVarP(&chainID, "channelID", "C", util.GetTestChainID(),
flags.StringVarP(&channelID, "channelID", "C", "",
fmt.Sprint("The channel on which this command should be executed"))
flags.StringVarP(&policy, "policy", "P", common.UndefinedParamValue,
fmt.Sprint("The endorsement policy associated to this chaincode"))
Expand Down
10 changes: 5 additions & 5 deletions peer/chaincode/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func chaincodeInvokeOrQuery(cmd *cobra.Command, args []string, invoke bool, cf *

proposalResp, err := ChaincodeInvokeOrQuery(
spec,
chainID,
channelID,
invoke,
cf.Signer,
cf.EndorserClient,
Expand Down Expand Up @@ -246,14 +246,14 @@ func InitCmdFactory(isEndorserRequired, isOrdererRequired bool) (*ChaincodeCmdFa
var broadcastClient common.BroadcastClient
if isOrdererRequired {
if len(orderingEndpoint) == 0 {
orderingEndpoints, err := common.GetOrdererEndpointOfChainFnc(chainID, signer, endorserClient)
orderingEndpoints, err := common.GetOrdererEndpointOfChainFnc(channelID, signer, endorserClient)
if err != nil {
return nil, fmt.Errorf("Error getting (%s) orderer endpoint: %s", chainID, err)
return nil, fmt.Errorf("Error getting (%s) orderer endpoint: %s", channelID, err)
}
if len(orderingEndpoints) == 0 {
return nil, fmt.Errorf("Error no orderer endpoint got for %s", chainID)
return nil, fmt.Errorf("Error no orderer endpoint got for %s", channelID)
}
logger.Infof("Get chain(%s) orderer endpoint: %s", chainID, orderingEndpoints[0])
logger.Infof("Get chain(%s) orderer endpoint: %s", channelID, orderingEndpoints[0])
orderingEndpoint = orderingEndpoints[0]
}

Expand Down
6 changes: 5 additions & 1 deletion peer/chaincode/instantiate.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package chaincode

import (
"errors"
"fmt"

protcommon "github.com/hyperledger/fabric/protos/common"
Expand Down Expand Up @@ -75,7 +76,7 @@ func instantiate(cmd *cobra.Command, cf *ChaincodeCmdFactory) (*protcommon.Envel
return nil, fmt.Errorf("Error serializing identity for %s: %s", cf.Signer.GetIdentifier(), err)
}

prop, _, err := utils.CreateDeployProposalFromCDS(chainID, cds, creator, policyMarshalled, []byte(escc), []byte(vscc))
prop, _, err := utils.CreateDeployProposalFromCDS(channelID, cds, creator, policyMarshalled, []byte(escc), []byte(vscc))
if err != nil {
return nil, fmt.Errorf("Error creating proposal %s: %s", chainFuncName, err)
}
Expand Down Expand Up @@ -108,6 +109,9 @@ func instantiate(cmd *cobra.Command, cf *ChaincodeCmdFactory) (*protcommon.Envel
// (hash) is printed to STDOUT for use by subsequent chaincode-related CLI
// commands.
func chaincodeDeploy(cmd *cobra.Command, args []string, cf *ChaincodeCmdFactory) error {
if channelID == "" {
return errors.New("The required parameter 'channelID' is empty. Rerun the command with -C flag")
}
var err error
if cf == nil {
cf, err = InitCmdFactory(true, true)
Expand Down
14 changes: 10 additions & 4 deletions peer/chaincode/instantiate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestInstantiateCmd(t *testing.T) {
}{
{
name: "successful",
args: []string{"-n", "example02", "-v", "anotherversion", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
args: []string{"-n", "example02", "-v", "anotherversion", "-C", "mychannel", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: false,
errMsg: "Run chaincode instantiate cmd error",
},
Expand All @@ -49,19 +49,25 @@ func TestInstantiateCmd(t *testing.T) {
},
{
name: "missing version",
args: []string{"-n", "example02", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
args: []string{"-n", "example02", "-C", "mychannel", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -v option",
},
{
name: "missing name",
args: []string{"-v", "anotherversion", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
args: []string{"-v", "anotherversion", "-C", "mychannel", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -n option",
},
{
name: "missing channelID",
args: []string{"-n", "example02", "-v", "anotherversion", "-c", "{\"Args\": [\"init\",\"a\",\"100\",\"b\",\"200\"]}"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -C option",
},
{
name: "missing ctor",
args: []string{"-n", "example02", "-v", "anotherversion"},
args: []string{"-n", "example02", "-C", "mychannel", "-v", "anotherversion"},
errorExpected: true,
errMsg: "Expected error executing instantiate command without the -c option",
},
Expand Down
4 changes: 4 additions & 0 deletions peer/chaincode/invoke.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package chaincode

import (
"errors"
"fmt"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -46,6 +47,9 @@ func invokeCmd(cf *ChaincodeCmdFactory) *cobra.Command {
}

func chaincodeInvoke(cmd *cobra.Command, args []string, cf *ChaincodeCmdFactory) error {
if channelID == "" {
return errors.New("The required parameter 'channelID' is empty. Rerun the command with -C flag")
}
var err error
if cf == nil {
cf, err = InitCmdFactory(true, true)
Expand Down
15 changes: 13 additions & 2 deletions peer/chaincode/invoke_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,23 @@ func TestInvokeCmd(t *testing.T) {
InitMSP()
mockCF, err := getMockChaincodeCmdFactory()
assert.NoError(t, err, "Error getting mock chaincode command factory")
// reset channelID, it might have been set by previous test
channelID = ""

// Error case 0: no channelID specified
cmd := invokeCmd(mockCF)
addFlags(cmd)
args := []string{"-n", "example02", "-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.Error(t, err, "'peer chaincode invoke' command should have returned error when called without -C flag")

// Success case
cmd = invokeCmd(mockCF)
addFlags(cmd)
args = []string{"-n", "example02", "-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}", "-C", "mychannel"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.NoError(t, err, "Run chaincode invoke cmd error")

// Error case 1: no orderer endpoints
Expand All @@ -65,7 +76,7 @@ func TestInvokeCmd(t *testing.T) {
}
cmd = invokeCmd(nil)
addFlags(cmd)
args = []string{"-n", "example02", "-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
args = []string{"-n", "example02", "-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}", "-C", "mychannel"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.Error(t, err)
Expand Down Expand Up @@ -128,7 +139,7 @@ func TestInvokeCmdEndorsementError(t *testing.T) {

cmd := invokeCmd(mockCF)
addFlags(cmd)
args := []string{"-n", "example02", "-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
args := []string{"-n", "example02", "-C", "mychannel", "-c", "{\"Args\": [\"invoke\",\"a\",\"b\",\"10\"]}"}
cmd.SetArgs(args)
err = cmd.Execute()
assert.Error(t, err, "Expected error executing invoke command")
Expand Down
8 changes: 6 additions & 2 deletions peer/chaincode/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ SPDX-License-Identifier: Apache-2.0
package chaincode

import (
"errors"
"fmt"

"github.com/golang/protobuf/proto"
Expand Down Expand Up @@ -45,6 +46,9 @@ func listCmd(cf *ChaincodeCmdFactory) *cobra.Command {
}

func getChaincodes(cmd *cobra.Command, cf *ChaincodeCmdFactory) error {
if channelID == "" {
return errors.New("The required parameter 'channelID' is empty. Rerun the command with -C flag")
}
var err error
if cf == nil {
cf, err = InitCmdFactory(true, false)
Expand All @@ -62,7 +66,7 @@ func getChaincodes(cmd *cobra.Command, cf *ChaincodeCmdFactory) error {
if getInstalledChaincodes && (!getInstantiatedChaincodes) {
prop, _, err = utils.CreateGetInstalledChaincodesProposal(creator)
} else if getInstantiatedChaincodes && (!getInstalledChaincodes) {
prop, _, err = utils.CreateGetChaincodesProposal(chainID, creator)
prop, _, err = utils.CreateGetChaincodesProposal(channelID, creator)
} else {
return fmt.Errorf("Must explicitly specify \"--installed\" or \"--instantiated\"")
}
Expand Down Expand Up @@ -91,7 +95,7 @@ func getChaincodes(cmd *cobra.Command, cf *ChaincodeCmdFactory) error {
if getInstalledChaincodes {
fmt.Println("Get installed chaincodes on peer:")
} else {
fmt.Printf("Get instantiated chaincodes on channel %s:\n", chainID)
fmt.Printf("Get instantiated chaincodes on channel %s:\n", channelID)
}
for _, chaincode := range cqr.Chaincodes {
fmt.Printf("%v\n", chaincode)
Expand Down
19 changes: 16 additions & 3 deletions peer/chaincode/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/peer/common"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/stretchr/testify/assert"
)

func TestChaincodeListCmd(t *testing.T) {
Expand Down Expand Up @@ -48,13 +49,19 @@ func TestChaincodeListCmd(t *testing.T) {
Signer: signer,
BroadcastClient: mockBroadcastClient,
}
// reset channelID, it might have been set by previous test
channelID = ""

// Get installed chaincodes
installedChaincodesCmd := listCmd(mockCF)

args := []string{"--installed"}
installedChaincodesCmd.SetArgs(args)
err = installedChaincodesCmd.Execute()
assert.Error(t, err, "Run chaincode list cmd to get installed chaincodes should fail if invoked without -C flag")

args = []string{"--installed", "-C", "mychannel"}
installedChaincodesCmd.SetArgs(args)
if err := installedChaincodesCmd.Execute(); err != nil {
t.Errorf("Run chaincode list cmd to get installed chaincodes error:%v", err)
}
Expand All @@ -63,10 +70,13 @@ func TestChaincodeListCmd(t *testing.T) {

// Get instantiated chaincodes
instantiatedChaincodesCmd := listCmd(mockCF)

args = []string{"--instantiated"}
instantiatedChaincodesCmd.SetArgs(args)
err = instantiatedChaincodesCmd.Execute()
assert.Error(t, err, "Run chaincode list cmd to get instantiated chaincodes should fail if invoked without -C flag")

args = []string{"--instantiated", "-C", "mychannel"}
instantiatedChaincodesCmd.SetArgs(args)
if err := instantiatedChaincodesCmd.Execute(); err != nil {
t.Errorf("Run chaincode list cmd to get instantiated chaincodes error:%v", err)
}
Expand All @@ -75,10 +85,13 @@ func TestChaincodeListCmd(t *testing.T) {

// Wrong case: Set both "--installed" and "--instantiated"
Cmd := listCmd(mockCF)

args = []string{"--installed", "--instantiated"}
Cmd.SetArgs(args)
err = Cmd.Execute()
assert.Error(t, err, "Run chaincode list cmd to get instantiated/installed chaincodes should fail if invoked without -C flag")

args = []string{"--installed", "--instantiated", "-C", "mychannel"}
Cmd.SetArgs(args)
expectErr := fmt.Errorf("Must explicitly specify \"--installed\" or \"--instantiated\"")
if err := Cmd.Execute(); err == nil || err.Error() != expectErr.Error() {
t.Errorf("Expect error: %s", expectErr)
Expand All @@ -89,7 +102,7 @@ func TestChaincodeListCmd(t *testing.T) {
// Wrong case: Miss "--intsalled" and "--instantiated"
nilCmd := listCmd(mockCF)

args = []string{}
args = []string{"-C", "mychannel"}
nilCmd.SetArgs(args)

expectErr = fmt.Errorf("Must explicitly specify \"--installed\" or \"--instantiated\"")
Expand Down
4 changes: 4 additions & 0 deletions peer/chaincode/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package chaincode

import (
"errors"
"fmt"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -52,6 +53,9 @@ func queryCmd(cf *ChaincodeCmdFactory) *cobra.Command {
}

func chaincodeQuery(cmd *cobra.Command, args []string, cf *ChaincodeCmdFactory) error {
if channelID == "" {
return errors.New("The required parameter 'channelID' is empty. Rerun the command with -C flag")
}
var err error
if cf == nil {
cf, err = InitCmdFactory(true, false)
Expand Down
Loading

0 comments on commit d203895

Please sign in to comment.