github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/core/scc/lscc/lscc_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  package lscc
    17  
    18  import (
    19  	"fmt"
    20  	"io/ioutil"
    21  	"os"
    22  	"strings"
    23  	"testing"
    24  
    25  	"github.com/golang/protobuf/proto"
    26  	"github.com/hyperledger/fabric/common/cauthdsl"
    27  	"github.com/hyperledger/fabric/common/util"
    28  	"github.com/hyperledger/fabric/core/chaincode/shim"
    29  	"github.com/hyperledger/fabric/core/common/ccpackage"
    30  	"github.com/hyperledger/fabric/core/common/ccprovider"
    31  	"github.com/hyperledger/fabric/core/common/sysccprovider"
    32  	//"github.com/hyperledger/fabric/core/container"
    33  	"archive/tar"
    34  	"bytes"
    35  	"compress/gzip"
    36  
    37  	"github.com/hyperledger/fabric/common/policies"
    38  	"github.com/hyperledger/fabric/core/policy"
    39  	"github.com/hyperledger/fabric/msp"
    40  	mspmgmt "github.com/hyperledger/fabric/msp/mgmt"
    41  	"github.com/hyperledger/fabric/msp/mgmt/testtools"
    42  	"github.com/hyperledger/fabric/protos/common"
    43  	putils "github.com/hyperledger/fabric/protos/utils"
    44  
    45  	cutil "github.com/hyperledger/fabric/core/container/util"
    46  	pb "github.com/hyperledger/fabric/protos/peer"
    47  	"github.com/hyperledger/fabric/protos/utils"
    48  )
    49  
    50  var lscctestpath = "/tmp/lscctest"
    51  
    52  type mocksccProviderFactory struct {
    53  }
    54  
    55  func (c *mocksccProviderFactory) NewSystemChaincodeProvider() sysccprovider.SystemChaincodeProvider {
    56  	return &mocksccProviderImpl{}
    57  }
    58  
    59  type mocksccProviderImpl struct {
    60  }
    61  
    62  func (c *mocksccProviderImpl) IsSysCC(name string) bool {
    63  	return true
    64  }
    65  
    66  func (c *mocksccProviderImpl) IsSysCCAndNotInvokableCC2CC(name string) bool {
    67  	return false
    68  }
    69  
    70  func register(stub *shim.MockStub, ccname string) error {
    71  	args := [][]byte{[]byte("register"), []byte(ccname)}
    72  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
    73  		return fmt.Errorf(string(res.Message))
    74  	}
    75  	return nil
    76  }
    77  
    78  func constructDeploymentSpec(name string, path string, version string, initArgs [][]byte, createFS bool) (*pb.ChaincodeDeploymentSpec, error) {
    79  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: &pb.ChaincodeID{Name: name, Path: path, Version: version}, Input: &pb.ChaincodeInput{Args: initArgs}}
    80  
    81  	codePackageBytes := bytes.NewBuffer(nil)
    82  	gz := gzip.NewWriter(codePackageBytes)
    83  	tw := tar.NewWriter(gz)
    84  
    85  	err := cutil.WriteBytesToPackage("src/garbage.go", []byte(name+path+version), tw)
    86  	if err != nil {
    87  		return nil, err
    88  	}
    89  
    90  	tw.Close()
    91  	gz.Close()
    92  
    93  	chaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes.Bytes()}
    94  
    95  	if createFS {
    96  		err := ccprovider.PutChaincodeIntoFS(chaincodeDeploymentSpec)
    97  		if err != nil {
    98  			return nil, err
    99  		}
   100  	}
   101  
   102  	return chaincodeDeploymentSpec, nil
   103  }
   104  
   105  //TestInstall tests the install function with various inputs
   106  func TestInstall(t *testing.T) {
   107  	path := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
   108  
   109  	testInstall(t, "example02", "0", path, "", "Alice")
   110  	testInstall(t, "example02-2", "1.0", path, "", "Alice")
   111  	testInstall(t, "example02.go", "0", path, InvalidChaincodeNameErr("example02.go").Error(), "Alice")
   112  	testInstall(t, "", "0", path, EmptyChaincodeNameErr("").Error(), "Alice")
   113  	testInstall(t, "example02", "1{}0", path, InvalidVersionErr("1{}0").Error(), "Alice")
   114  	testInstall(t, "example02", "0", path, "Authorization for INSTALL on", "Bob")
   115  }
   116  
   117  func testInstall(t *testing.T, ccname string, version string, path string, expectedErrorMsg string, caller string) {
   118  	scc := new(LifeCycleSysCC)
   119  	stub := shim.NewMockStub("lscc", scc)
   120  
   121  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   122  		fmt.Println("Init failed", string(res.Message))
   123  		t.FailNow()
   124  	}
   125  
   126  	// Init the policy checker
   127  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   128  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   129  		Managers: map[string]policies.Manager{
   130  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   131  		},
   132  	}
   133  	scc.policyChecker = policy.NewPolicyChecker(
   134  		policyManagerGetter,
   135  		identityDeserializer,
   136  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   137  	)
   138  
   139  	cds, err := constructDeploymentSpec(ccname, path, version, [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, false)
   140  	if err != nil {
   141  		t.FailNow()
   142  	}
   143  	var b []byte
   144  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   145  		t.FailNow()
   146  	}
   147  
   148  	//constructDeploymentSpec puts the depspec on the FS. This should succeed
   149  	args := [][]byte{[]byte(INSTALL), b}
   150  
   151  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte(caller), []byte("msg1"))
   152  	identityDeserializer.Msg = sProp.ProposalBytes
   153  	sProp.Signature = sProp.ProposalBytes
   154  
   155  	if expectedErrorMsg == "" {
   156  		defer os.Remove(lscctestpath + "/" + ccname + "." + version)
   157  		if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   158  			t.FailNow()
   159  		}
   160  	} else {
   161  		if res := stub.MockInvokeWithSignedProposal("1", args, sProp); !strings.HasPrefix(string(res.Message), expectedErrorMsg) {
   162  			t.Logf("Received error: [%s]", res.Message)
   163  			t.FailNow()
   164  		}
   165  	}
   166  
   167  	args = [][]byte{[]byte(GETINSTALLEDCHAINCODES)}
   168  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   169  	identityDeserializer.Msg = sProp.ProposalBytes
   170  	sProp.Signature = sProp.ProposalBytes
   171  	res := stub.MockInvokeWithSignedProposal("1", args, sProp)
   172  	if res.Status != shim.OK {
   173  		t.FailNow()
   174  	}
   175  
   176  	cqr := &pb.ChaincodeQueryResponse{}
   177  	err = proto.Unmarshal(res.Payload, cqr)
   178  	if err != nil {
   179  		t.FailNow()
   180  	}
   181  
   182  	if expectedErrorMsg == "" {
   183  		// installed one chaincode so query should return an array with one chaincode
   184  		if len(cqr.GetChaincodes()) != 1 {
   185  			t.Logf("Expected 1 chaincode, found %d\n", len(cqr.GetChaincodes()))
   186  			t.FailNow()
   187  		}
   188  
   189  		// check that the ChaincodeInfo values match the input values
   190  		if cqr.GetChaincodes()[0].Name != ccname || cqr.GetChaincodes()[0].Version != version || cqr.GetChaincodes()[0].Path != path {
   191  			t.FailNow()
   192  		}
   193  	} else {
   194  		// we expected an error so no chaincodes should have installed
   195  		if len(cqr.GetChaincodes()) != 0 {
   196  			t.Logf("Expected 0 chaincodes, found %d\n", len(cqr.GetChaincodes()))
   197  			t.FailNow()
   198  		}
   199  	}
   200  }
   201  
   202  //TestReinstall tests the install function
   203  func TestReinstall(t *testing.T) {
   204  	scc := new(LifeCycleSysCC)
   205  	stub := shim.NewMockStub("lscc", scc)
   206  
   207  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   208  		fmt.Println("Init failed", string(res.Message))
   209  		t.FailNow()
   210  	}
   211  
   212  	//note that this puts the code on the filesyste....
   213  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   214  	if err != nil {
   215  		t.FailNow()
   216  	}
   217  	defer os.Remove(lscctestpath + "/example02.0")
   218  	var b []byte
   219  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   220  		t.FailNow()
   221  	}
   222  
   223  	//constructDeploymentSpec puts the depspec on the FS. This should fail
   224  	args := [][]byte{[]byte(INSTALL), b}
   225  	if res := stub.MockInvoke("1", args); res.Status == shim.OK {
   226  		t.FailNow()
   227  	}
   228  }
   229  
   230  //TestInvalidCodeDeploy tests the deploy function with invalid code package
   231  func TestInvalidCodeDeploy(t *testing.T) {
   232  	scc := new(LifeCycleSysCC)
   233  	stub := shim.NewMockStub("lscc", scc)
   234  
   235  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   236  		fmt.Println("Init failed", string(res.Message))
   237  		t.FailNow()
   238  	}
   239  
   240  	baddepspec := []byte("bad deploy spec")
   241  	args := [][]byte{[]byte(DEPLOY), []byte("test"), baddepspec}
   242  	res := stub.MockInvoke("1", args)
   243  	if res.Status == shim.OK {
   244  		t.Logf("Expected failure")
   245  		t.FailNow()
   246  	}
   247  }
   248  
   249  // TestDeploy tests the deploy function with various inputs for basic use cases
   250  // (and stops short of actually running the chaincode). More advanced tests like
   251  // redeploying, multiple deployments, and other failure cases that don't match
   252  // this standard test case pattern are handled in other test cases below.
   253  // Note: the forceBlankCCName and forceBlankVersion flags are necessary because
   254  // constructDeploymentSpec() with the createFS flag set to true places the
   255  // chaincode onto the filesystem to install it before it then attempts to
   256  // instantiate the chaincode
   257  func TestDeploy(t *testing.T) {
   258  	path := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
   259  
   260  	testDeploy(t, "example02", "0", path, false, false, "")
   261  	testDeploy(t, "example02", "1.0", path, false, false, "")
   262  	testDeploy(t, "example02", "0", path, true, false, EmptyChaincodeNameErr("").Error())
   263  	testDeploy(t, "example02", "0", path, false, true, EmptyVersionErr("example02").Error())
   264  	testDeploy(t, "example02.go", "0", path, false, false, InvalidChaincodeNameErr("example02.go").Error())
   265  	testDeploy(t, "example02", "1{}0", path, false, false, InvalidVersionErr("1{}0").Error())
   266  	testDeploy(t, "example02", "0", path, true, true, EmptyChaincodeNameErr("").Error())
   267  }
   268  
   269  func testDeploy(t *testing.T, ccname string, version string, path string, forceBlankCCName bool, forceBlankVersion bool, expectedErrorMsg string) {
   270  	scc := new(LifeCycleSysCC)
   271  	stub := shim.NewMockStub("lscc", scc)
   272  
   273  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   274  		t.Logf("Init failed: %s", string(res.Message))
   275  		t.FailNow()
   276  	}
   277  
   278  	// Init the policy checker
   279  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   280  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   281  		Managers: map[string]policies.Manager{
   282  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   283  		},
   284  	}
   285  	scc.policyChecker = policy.NewPolicyChecker(
   286  		policyManagerGetter,
   287  		identityDeserializer,
   288  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   289  	)
   290  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   291  	identityDeserializer.Msg = sProp.ProposalBytes
   292  	sProp.Signature = sProp.ProposalBytes
   293  
   294  	cds, err := constructDeploymentSpec(ccname, path, version, [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   295  	if err != nil {
   296  		t.FailNow()
   297  	}
   298  	defer os.Remove(lscctestpath + "/" + ccname + "." + version)
   299  	if forceBlankCCName {
   300  		cds.ChaincodeSpec.ChaincodeId.Name = ""
   301  	}
   302  	if forceBlankVersion {
   303  		cds.ChaincodeSpec.ChaincodeId.Version = ""
   304  	}
   305  	var b []byte
   306  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   307  		t.FailNow()
   308  	}
   309  
   310  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
   311  	res := stub.MockInvoke("1", args)
   312  
   313  	if expectedErrorMsg == "" {
   314  		if res.Status != shim.OK {
   315  			t.FailNow()
   316  		}
   317  	} else {
   318  		if string(res.Message) != expectedErrorMsg {
   319  			t.Logf("Get error: %s", res.Message)
   320  			t.FailNow()
   321  		}
   322  	}
   323  
   324  	args = [][]byte{[]byte(GETCHAINCODES)}
   325  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
   326  	if res.Status != shim.OK {
   327  		t.FailNow()
   328  	}
   329  
   330  	cqr := &pb.ChaincodeQueryResponse{}
   331  	err = proto.Unmarshal(res.Payload, cqr)
   332  	if err != nil {
   333  		t.FailNow()
   334  	}
   335  
   336  	if expectedErrorMsg == "" {
   337  		// instantiated one chaincode so query should return an array with one chaincode
   338  		if len(cqr.GetChaincodes()) != 1 {
   339  			t.Logf("Expected 1 chaincode, found %d\n", len(cqr.GetChaincodes()))
   340  			t.FailNow()
   341  		}
   342  
   343  		// check that the ChaincodeInfo values match the input values
   344  		if cqr.GetChaincodes()[0].Name != ccname || cqr.GetChaincodes()[0].Version != version || cqr.GetChaincodes()[0].Path != path {
   345  			t.FailNow()
   346  		}
   347  
   348  		args = [][]byte{[]byte(GETCCINFO), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   349  		if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   350  			t.FailNow()
   351  		}
   352  	} else {
   353  		// instantiated zero chaincodes so query should return a zero-length array
   354  		if len(cqr.GetChaincodes()) != 0 {
   355  			t.Logf("Expected 0 chaincodes, found %d\n", len(cqr.GetChaincodes()))
   356  			t.FailNow()
   357  		}
   358  	}
   359  }
   360  
   361  //TestRedeploy tests the redeploying will fail function(and fail with "exists" error)
   362  func TestRedeploy(t *testing.T) {
   363  	scc := new(LifeCycleSysCC)
   364  	stub := shim.NewMockStub("lscc", scc)
   365  
   366  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   367  		fmt.Println("Init failed", string(res.Message))
   368  		t.FailNow()
   369  	}
   370  
   371  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   372  	if err != nil {
   373  		t.FailNow()
   374  	}
   375  	defer os.Remove(lscctestpath + "/example02.0")
   376  	var b []byte
   377  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   378  		t.FailNow()
   379  	}
   380  
   381  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
   382  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   383  		t.FailNow()
   384  	}
   385  
   386  	//this should fail with exists error
   387  	args = [][]byte{[]byte(DEPLOY), []byte("test"), b}
   388  	res := stub.MockInvoke("1", args)
   389  	if string(res.Message) != ExistsErr("example02").Error() {
   390  		t.FailNow()
   391  	}
   392  }
   393  
   394  //TestMultipleDeploy tests deploying multiple chaincodeschaincodes
   395  func TestMultipleDeploy(t *testing.T) {
   396  	scc := new(LifeCycleSysCC)
   397  	stub := shim.NewMockStub("lscc", scc)
   398  
   399  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   400  		fmt.Println("Init failed", string(res.Message))
   401  		t.FailNow()
   402  	}
   403  
   404  	// Init the policy checker
   405  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   406  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   407  		Managers: map[string]policies.Manager{
   408  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   409  		},
   410  	}
   411  	scc.policyChecker = policy.NewPolicyChecker(
   412  		policyManagerGetter,
   413  		identityDeserializer,
   414  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   415  	)
   416  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   417  	identityDeserializer.Msg = sProp.ProposalBytes
   418  	sProp.Signature = sProp.ProposalBytes
   419  
   420  	//deploy 02
   421  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   422  	if err != nil {
   423  		t.FailNow()
   424  	}
   425  	defer os.Remove(lscctestpath + "/example02.0")
   426  	var b []byte
   427  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   428  		t.FailNow()
   429  	}
   430  
   431  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
   432  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   433  		t.FailNow()
   434  	}
   435  
   436  	args = [][]byte{[]byte(GETCCINFO), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   437  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   438  		t.FailNow()
   439  	}
   440  
   441  	//deploy 01
   442  	cds, err = constructDeploymentSpec("example01", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   443  	if err != nil {
   444  		t.FailNow()
   445  	}
   446  	defer os.Remove(lscctestpath + "/example01.0")
   447  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   448  		t.FailNow()
   449  	}
   450  
   451  	args = [][]byte{[]byte(DEPLOY), []byte("test"), b}
   452  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   453  		t.FailNow()
   454  	}
   455  
   456  	args = [][]byte{[]byte(GETCCINFO), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   457  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   458  		t.FailNow()
   459  	}
   460  
   461  	args = [][]byte{[]byte(GETCHAINCODES)}
   462  	res := stub.MockInvokeWithSignedProposal("1", args, sProp)
   463  	if res.Status != shim.OK {
   464  		t.FailNow()
   465  	}
   466  
   467  	cqr := &pb.ChaincodeQueryResponse{}
   468  	err = proto.Unmarshal(res.Payload, cqr)
   469  	if err != nil {
   470  		t.FailNow()
   471  	}
   472  
   473  	// deployed two chaincodes so query should return an array with two chaincodes
   474  	if len(cqr.GetChaincodes()) != 2 {
   475  		t.FailNow()
   476  	}
   477  
   478  }
   479  
   480  //TestRetryFailedDeploy tests re-deploying after a failure
   481  func TestRetryFailedDeploy(t *testing.T) {
   482  	scc := new(LifeCycleSysCC)
   483  	stub := shim.NewMockStub("lscc", scc)
   484  
   485  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   486  		fmt.Println("Init failed", string(res.Message))
   487  		t.FailNow()
   488  	}
   489  	// Init the policy checker
   490  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   491  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   492  		Managers: map[string]policies.Manager{
   493  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   494  		},
   495  	}
   496  	scc.policyChecker = policy.NewPolicyChecker(
   497  		policyManagerGetter,
   498  		identityDeserializer,
   499  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   500  	)
   501  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   502  	identityDeserializer.Msg = sProp.ProposalBytes
   503  	sProp.Signature = sProp.ProposalBytes
   504  
   505  	//deploy 02
   506  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   507  	if err != nil {
   508  		t.FailNow()
   509  	}
   510  	defer os.Remove(lscctestpath + "/example02.0")
   511  	var b []byte
   512  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   513  		t.FailNow()
   514  	}
   515  
   516  	//send invalid chain name name that should fail
   517  	args := [][]byte{[]byte(DEPLOY), []byte(""), b}
   518  	res := stub.MockInvoke("1", args)
   519  	if res.Status == shim.OK {
   520  		//expected error but got success
   521  		t.FailNow()
   522  	}
   523  
   524  	if string(res.Message) != InvalidChainNameErr("").Error() {
   525  		//expected invalid chain name
   526  		t.FailNow()
   527  	}
   528  
   529  	//deploy correctly now
   530  	args = [][]byte{[]byte(DEPLOY), []byte("test"), b}
   531  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   532  		t.FailNow()
   533  	}
   534  
   535  	//get the deploymentspec
   536  	args = [][]byte{[]byte(GETDEPSPEC), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   537  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK || res.Payload == nil {
   538  		t.FailNow()
   539  	}
   540  }
   541  
   542  //TestTamperChaincode modifies the chaincode on the FS after deploy
   543  func TestTamperChaincode(t *testing.T) {
   544  	scc := new(LifeCycleSysCC)
   545  	stub := shim.NewMockStub("lscc", scc)
   546  
   547  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   548  		fmt.Println("Init failed", string(res.Message))
   549  		t.FailNow()
   550  	}
   551  
   552  	// Init the policy checker
   553  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   554  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   555  		Managers: map[string]policies.Manager{
   556  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   557  		},
   558  	}
   559  	scc.policyChecker = policy.NewPolicyChecker(
   560  		policyManagerGetter,
   561  		identityDeserializer,
   562  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   563  	)
   564  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   565  	identityDeserializer.Msg = sProp.ProposalBytes
   566  	sProp.Signature = sProp.ProposalBytes
   567  
   568  	//deploy 01
   569  	cds, err := constructDeploymentSpec("example01", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01", "0", [][]byte{[]byte("init"), []byte("a"), []byte("1"), []byte("b"), []byte("2")}, true)
   570  	if err != nil {
   571  		t.Logf("Could not construct example01.0 [%s]", err)
   572  		t.FailNow()
   573  	}
   574  
   575  	defer os.Remove(lscctestpath + "/example01.0")
   576  
   577  	var b []byte
   578  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   579  		t.Logf("Could not construct example01.0")
   580  		t.FailNow()
   581  	}
   582  
   583  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
   584  	res := stub.MockInvoke("1", args)
   585  	if res.Status != shim.OK {
   586  		t.Logf("Could not deploy example01.0")
   587  		t.FailNow()
   588  	}
   589  
   590  	//deploy 02
   591  	cds, err = constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   592  	if err != nil {
   593  		t.FailNow()
   594  	}
   595  
   596  	defer os.Remove(lscctestpath + "/example02.0")
   597  
   598  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   599  		t.FailNow()
   600  	}
   601  
   602  	//deploy correctly now
   603  	args = [][]byte{[]byte(DEPLOY), []byte("test"), b}
   604  	if res = stub.MockInvoke("1", args); res.Status != shim.OK {
   605  		t.Logf("Could not deploy example02.0")
   606  		t.FailNow()
   607  	}
   608  
   609  	//remove the old file...
   610  	os.Remove(lscctestpath + "/example02.0")
   611  
   612  	//read 01 and ...
   613  	if b, err = ioutil.ReadFile(lscctestpath + "/example01.0"); err != nil {
   614  		t.Logf("Could not read back example01.0")
   615  		t.FailNow()
   616  	}
   617  
   618  	//...brute force replace 02 with bytes from 01
   619  	if err = ioutil.WriteFile(lscctestpath+"/example02.0", b, 0644); err != nil {
   620  		t.Logf("Could not write to example02.0")
   621  		t.FailNow()
   622  	}
   623  
   624  	//get the deploymentspec
   625  	args = [][]byte{[]byte(GETDEPSPEC), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   626  	if res = stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status == shim.OK {
   627  		t.Logf("Expected error on tampering files but succeeded")
   628  		t.FailNow()
   629  	}
   630  
   631  	//look specifically for Invalid error
   632  	expectedErr := InvalidCCOnFSError("").Error()
   633  	if strings.Index(res.Message, expectedErr) < 0 {
   634  		t.Logf("Expected prefix %s on error but appeared to have got a different error : %+v", expectedErr, res)
   635  		t.FailNow()
   636  	}
   637  }
   638  
   639  //TestIPolDeploy tests chaincode deploy with an instantiation policy
   640  func TestIPolDeploy(t *testing.T) {
   641  	// default policy, this should succeed
   642  	testIPolDeploy(t, "", true)
   643  	// policy involving an unknown ORG, this should fail
   644  	testIPolDeploy(t, "AND('ORG.admin')", false)
   645  }
   646  
   647  func testIPolDeploy(t *testing.T, iPol string, successExpected bool) {
   648  	scc := new(LifeCycleSysCC)
   649  	stub := shim.NewMockStub("lscc", scc)
   650  
   651  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   652  		t.Fatalf("Init failed [%s]", string(res.Message))
   653  	}
   654  
   655  	// Init the policy checker
   656  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   657  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   658  		Managers: map[string]policies.Manager{
   659  			chainid: &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   660  		},
   661  	}
   662  	scc.policyChecker = policy.NewPolicyChecker(
   663  		policyManagerGetter,
   664  		identityDeserializer,
   665  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   666  	)
   667  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   668  	identityDeserializer.Msg = sProp.ProposalBytes
   669  	sProp.Signature = sProp.ProposalBytes
   670  
   671  	// create deployment spec, don't write to disk, just marshal it to be used in a signed dep spec
   672  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, false)
   673  	if err != nil {
   674  		t.Fatalf("Error creating deployment spec: [%s]", err)
   675  	}
   676  	// create an instantiation policy
   677  	var ip *common.SignaturePolicyEnvelope
   678  	ip = cauthdsl.SignedByMspAdmin(mspid)
   679  	if iPol != "" {
   680  		ip, err = cauthdsl.FromString(iPol)
   681  		if err != nil {
   682  			t.Fatalf("Error creating instantiation policy %s: [%s]", iPol, err)
   683  		}
   684  	}
   685  	// create signed dep spec
   686  	cdsbytes, err := proto.Marshal(cds)
   687  	if err != nil {
   688  		t.Fatalf("Marshalling CDS failed: [%s]", err)
   689  	}
   690  	objToWrite, err := ccpackage.OwnerCreateSignedCCDepSpec(cds, ip, nil)
   691  	if err != nil {
   692  		t.Fatalf("Failed to create Signed CDS envelope %s", err)
   693  	}
   694  	// write it to disk
   695  	bytesToWrite, err := proto.Marshal(objToWrite)
   696  	if err != nil {
   697  		t.Fatalf("Failed to marshal Signed CDS envelope %s", err)
   698  	}
   699  	fileToWrite := lscctestpath + "/example02.0"
   700  	err = ioutil.WriteFile(fileToWrite, bytesToWrite, 0700)
   701  	if err != nil {
   702  		t.Fatalf("Failed to write Signed CDS envelope to disk: %s", err)
   703  	}
   704  	defer os.Remove(lscctestpath + "/example02.0")
   705  
   706  	// invoke deploy with a signed proposal that will be evaluated based on the policy
   707  	prop, _, err := putils.CreateChaincodeProposal(
   708  		common.HeaderType_ENDORSER_TRANSACTION,
   709  		chainid,
   710  		&pb.ChaincodeInvocationSpec{ChaincodeSpec: &pb.ChaincodeSpec{}},
   711  		sid)
   712  	if err != nil {
   713  		t.Fatalf("Error creating signed CC proposal [%s]", err)
   714  	}
   715  	sProp2, err := putils.GetSignedProposal(prop, id)
   716  	if err != nil {
   717  		t.Fatalf("Error getting signed proposal [%s]", err)
   718  	}
   719  	args := [][]byte{[]byte(DEPLOY), []byte(chainid), cdsbytes}
   720  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp2); res.Status != shim.OK {
   721  		if successExpected {
   722  			t.Fatalf("Deploy failed %s", res)
   723  		}
   724  	}
   725  
   726  	args = [][]byte{[]byte(GETCCINFO), []byte(chainid), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   727  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   728  		if successExpected {
   729  			t.Fatalf("GetCCInfo failed %s", res)
   730  		}
   731  	}
   732  }
   733  
   734  // TestUpgrade tests the upgrade function with various inputs for basic use cases
   735  func TestUpgrade(t *testing.T) {
   736  	path := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
   737  
   738  	testUpgrade(t, "example02", "0", "example02", "1", path, "")
   739  	testUpgrade(t, "example02", "0", "example02", "", path, EmptyVersionErr("example02").Error())
   740  	testUpgrade(t, "example02", "0", "example02", "0", path, IdenticalVersionErr("example02").Error())
   741  	testUpgrade(t, "example02", "0", "example03", "1", path, NotFoundErr("test").Error())
   742  	testUpgrade(t, "example02", "0", "example02", "1{}0", path, InvalidVersionErr("1{}0").Error())
   743  	testUpgrade(t, "example02", "0", "example*02", "1{}0", path, InvalidChaincodeNameErr("example*02").Error())
   744  	testUpgrade(t, "example02", "0", "", "1", path, EmptyChaincodeNameErr("").Error())
   745  }
   746  
   747  func testUpgrade(t *testing.T, ccname string, version string, newccname string, newversion string, path string, expectedErrorMsg string) {
   748  	scc := new(LifeCycleSysCC)
   749  	stub := shim.NewMockStub("lscc", scc)
   750  
   751  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   752  		fmt.Println("Init failed", string(res.Message))
   753  		t.FailNow()
   754  	}
   755  
   756  	cds, err := constructDeploymentSpec(ccname, path, version, [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   757  	if err != nil {
   758  		t.FailNow()
   759  	}
   760  	defer os.Remove(lscctestpath + "/" + ccname + "." + version)
   761  	var b []byte
   762  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   763  		t.Fatalf("Marshal DeploymentSpec failed")
   764  	}
   765  
   766  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
   767  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   768  		t.Fatalf("Deploy chaincode error: %v", err)
   769  	}
   770  
   771  	var newCds *pb.ChaincodeDeploymentSpec
   772  	// check to see if we've already created the deployment spec on the filesystem
   773  	// in the above step for the upgrade version
   774  	if ccname == newccname && version == newversion {
   775  		newCds, err = constructDeploymentSpec(newccname, path, newversion, [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, false)
   776  	} else {
   777  		newCds, err = constructDeploymentSpec(newccname, path, newversion, [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   778  	}
   779  	if err != nil {
   780  		t.FailNow()
   781  	}
   782  	defer os.Remove(lscctestpath + "/" + newccname + "." + newversion)
   783  	var newb []byte
   784  	if newb, err = proto.Marshal(newCds); err != nil || newb == nil {
   785  		t.Fatalf("Marshal DeploymentSpec failed")
   786  	}
   787  
   788  	args = [][]byte{[]byte(UPGRADE), []byte("test"), newb}
   789  	res := stub.MockInvoke("1", args)
   790  	if expectedErrorMsg == "" {
   791  		if res.Status != shim.OK {
   792  			t.Fatalf("Upgrade chaincode error: %v", err)
   793  		}
   794  
   795  		cd := &ccprovider.ChaincodeData{}
   796  		if err = proto.Unmarshal(res.Payload, cd); err != nil {
   797  			t.Fatalf("Upgrade chaincode could not unmarshal response")
   798  		}
   799  
   800  		newVer := cd.Version
   801  
   802  		expectVer := "1"
   803  		if newVer != expectVer {
   804  			t.Fatalf("Upgrade chaincode version error, expected %s, got %s", expectVer, newVer)
   805  		}
   806  	} else {
   807  		if string(res.Message) != expectedErrorMsg {
   808  			t.Logf("Received error message: %s", res.Message)
   809  			t.FailNow()
   810  		}
   811  	}
   812  }
   813  
   814  //TestIPolUpgrade tests chaincode deploy with an instantiation policy
   815  func TestIPolUpgrade(t *testing.T) {
   816  	// default policy, this should succeed
   817  	testIPolUpgrade(t, "", true)
   818  	// policy involving an unknown ORG, this should fail
   819  	testIPolUpgrade(t, "AND('ORG.admin')", false)
   820  }
   821  
   822  func testIPolUpgrade(t *testing.T, iPol string, successExpected bool) {
   823  	// deploy version 0 with a default instantiation policy, this should succeed in any case
   824  	scc := new(LifeCycleSysCC)
   825  	stub := shim.NewMockStub("lscc", scc)
   826  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   827  		fmt.Println("Init failed", string(res.Message))
   828  		t.FailNow()
   829  	}
   830  	// Init the policy checker
   831  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   832  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   833  		Managers: map[string]policies.Manager{
   834  			chainid: &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   835  		},
   836  	}
   837  	scc.policyChecker = policy.NewPolicyChecker(
   838  		policyManagerGetter,
   839  		identityDeserializer,
   840  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   841  	)
   842  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   843  	identityDeserializer.Msg = sProp.ProposalBytes
   844  	sProp.Signature = sProp.ProposalBytes
   845  	// create deployment spec, don't write to disk, just marshal it to be used in a signed dep spec
   846  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, false)
   847  	if err != nil {
   848  		t.Fatalf("Error creating deployment spec: [%s]", err)
   849  	}
   850  	// create an instantiation policy
   851  	ip := cauthdsl.SignedByMspAdmin(mspid)
   852  	// create signed dep spec
   853  	cdsbytes, err := proto.Marshal(cds)
   854  	if err != nil {
   855  		t.Fatalf("Marshalling CDS failed: [%s]", err)
   856  	}
   857  	objToWrite, err := ccpackage.OwnerCreateSignedCCDepSpec(cds, ip, nil)
   858  	if err != nil {
   859  		t.Fatalf("Failed to create Signed CDS envelope %s", err)
   860  	}
   861  	// write it to disk
   862  	bytesToWrite, err := proto.Marshal(objToWrite)
   863  	if err != nil {
   864  		t.Fatalf("Failed to marshal Signed CDS envelope %s", err)
   865  	}
   866  	fileToWrite := lscctestpath + "/example02.0"
   867  	err = ioutil.WriteFile(fileToWrite, bytesToWrite, 0700)
   868  	if err != nil {
   869  		t.Fatalf("Failed to write CC to disk: %s", err)
   870  	}
   871  	defer os.Remove(lscctestpath + "/example02.0")
   872  	// invoke deploy with a signed proposal that will be evaluated based on the policy
   873  	prop, _, err := putils.CreateChaincodeProposal(
   874  		common.HeaderType_ENDORSER_TRANSACTION,
   875  		chainid,
   876  		&pb.ChaincodeInvocationSpec{ChaincodeSpec: &pb.ChaincodeSpec{}},
   877  		sid)
   878  	if err != nil {
   879  		t.Fatalf("Error creating signed CC proposal [%s]", err)
   880  	}
   881  	sProp2, err := putils.GetSignedProposal(prop, id)
   882  	if err != nil {
   883  		t.Fatalf("Error getting signed proposal [%s]", err)
   884  	}
   885  	args := [][]byte{[]byte(DEPLOY), []byte(chainid), cdsbytes}
   886  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp2); res.Status != shim.OK {
   887  		t.Fatalf("Deploy failed %s", res)
   888  	}
   889  	args = [][]byte{[]byte(GETCCINFO), []byte(chainid), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   890  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   891  		t.Fatalf("GetCCInfo after deploy failed %s", res)
   892  	}
   893  
   894  	// here starts the interesting part for upgrade
   895  	// create deployment spec
   896  	cds, err = constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "1", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, false)
   897  	if err != nil {
   898  		t.Fatalf("Error creating deployment spec: [%s]", err)
   899  	}
   900  	cdsbytes, err = proto.Marshal(cds)
   901  	if err != nil {
   902  		t.Fatalf("Marshalling CDS failed: [%s]", err)
   903  	}
   904  	// create the instantiation policy
   905  	if iPol != "" {
   906  		ip, err = cauthdsl.FromString(iPol)
   907  		if err != nil {
   908  			t.Fatalf("Error creating instantiation policy %s: [%s]", iPol, err)
   909  		}
   910  	}
   911  	// create the signed ccpackage of the new version
   912  	objToWrite, err = ccpackage.OwnerCreateSignedCCDepSpec(cds, ip, nil)
   913  	if err != nil {
   914  		t.Fatalf("Failed to create Signed CDS envelope %s", err)
   915  	}
   916  	bytesToWrite, err = proto.Marshal(objToWrite)
   917  	if err != nil {
   918  		t.Fatalf("Failed to marshal Signed CDS envelope %s", err)
   919  	}
   920  	fileToWrite = lscctestpath + "/example02.1"
   921  	err = ioutil.WriteFile(fileToWrite, bytesToWrite, 0700)
   922  	if err != nil {
   923  		t.Fatalf("Failed to write CC to disk: %s", err)
   924  	}
   925  	defer os.Remove(lscctestpath + "/example02.1")
   926  
   927  	// invoke upgrade with a signed proposal that will be evaluated based on the policy
   928  	args = [][]byte{[]byte(UPGRADE), []byte(chainid), cdsbytes}
   929  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp2); res.Status != shim.OK {
   930  		if successExpected {
   931  			t.Fatalf("Upgrade failed %s", res)
   932  		}
   933  	}
   934  	args = [][]byte{[]byte(GETCCINFO), []byte(chainid), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   935  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   936  		if successExpected {
   937  			t.Fatalf("GetCCInfo failed")
   938  		}
   939  	}
   940  }
   941  
   942  //TestGetAPIsWithoutInstall get functions should return the right responses when chaicode is on
   943  //ledger but not on FS
   944  func TestGetAPIsWithoutInstall(t *testing.T) {
   945  	scc := new(LifeCycleSysCC)
   946  	stub := shim.NewMockStub("lscc", scc)
   947  
   948  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
   949  		fmt.Println("Init failed", string(res.Message))
   950  		t.FailNow()
   951  	}
   952  	// Init the policy checker
   953  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
   954  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
   955  		Managers: map[string]policies.Manager{
   956  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
   957  		},
   958  	}
   959  	scc.policyChecker = policy.NewPolicyChecker(
   960  		policyManagerGetter,
   961  		identityDeserializer,
   962  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
   963  	)
   964  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
   965  	identityDeserializer.Msg = sProp.ProposalBytes
   966  	sProp.Signature = sProp.ProposalBytes
   967  
   968  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
   969  
   970  	var b []byte
   971  	if b, err = proto.Marshal(cds); err != nil || b == nil {
   972  		t.FailNow()
   973  	}
   974  
   975  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
   976  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   977  		t.FailNow()
   978  	}
   979  
   980  	//Force remove CC
   981  	os.Remove(lscctestpath + "/example02.0")
   982  
   983  	//GETCCINFO should still work
   984  	args = [][]byte{[]byte(GETCCINFO), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   985  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   986  		t.FailNow()
   987  	}
   988  
   989  	//GETCCDATA should still work
   990  	args = [][]byte{[]byte(GETCCDATA), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   991  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status != shim.OK {
   992  		t.FailNow()
   993  	}
   994  
   995  	//GETDEPSPEC should not work
   996  	args = [][]byte{[]byte(GETDEPSPEC), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
   997  	if res := stub.MockInvokeWithSignedProposal("1", args, sProp); res.Status == shim.OK {
   998  		t.FailNow()
   999  	}
  1000  
  1001  	// get instantiated chaincodes
  1002  	args = [][]byte{[]byte(GETCHAINCODES)}
  1003  	res := stub.MockInvokeWithSignedProposal("1", args, sProp)
  1004  	if res.Status != shim.OK {
  1005  		t.FailNow()
  1006  	}
  1007  
  1008  	cqr := &pb.ChaincodeQueryResponse{}
  1009  	err = proto.Unmarshal(res.Payload, cqr)
  1010  	if err != nil {
  1011  		t.FailNow()
  1012  	}
  1013  
  1014  	// one chaincode instantiated so query should return an array with one
  1015  	// chaincode
  1016  	if len(cqr.GetChaincodes()) != 1 {
  1017  		t.FailNow()
  1018  	}
  1019  
  1020  	// get installed chaincodes
  1021  	args = [][]byte{[]byte(GETINSTALLEDCHAINCODES)}
  1022  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1023  	if res.Status != shim.OK {
  1024  		t.FailNow()
  1025  	}
  1026  
  1027  	cqr = &pb.ChaincodeQueryResponse{}
  1028  	err = proto.Unmarshal(res.Payload, cqr)
  1029  	if err != nil {
  1030  		t.FailNow()
  1031  	}
  1032  
  1033  	// no chaincodes installed to FS so query should return an array with zero
  1034  	// chaincodes
  1035  	if len(cqr.GetChaincodes()) != 0 {
  1036  		t.FailNow()
  1037  	}
  1038  
  1039  }
  1040  
  1041  // TestGetInstalledChaincodesAccessRights verifies that only authorized parties can call
  1042  // the GETINSTALLEDCHAINCODES function
  1043  func TestGetInstalledChaincodesAccessRights(t *testing.T) {
  1044  	scc := new(LifeCycleSysCC)
  1045  	stub := shim.NewMockStub("lscc", scc)
  1046  
  1047  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
  1048  		fmt.Println("Init failed", string(res.Message))
  1049  		t.FailNow()
  1050  	}
  1051  
  1052  	// Init the policy checker
  1053  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
  1054  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
  1055  		Managers: map[string]policies.Manager{
  1056  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
  1057  		},
  1058  	}
  1059  	scc.policyChecker = policy.NewPolicyChecker(
  1060  		policyManagerGetter,
  1061  		identityDeserializer,
  1062  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
  1063  	)
  1064  
  1065  	// Should pass
  1066  	args := [][]byte{[]byte(GETINSTALLEDCHAINCODES)}
  1067  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
  1068  	identityDeserializer.Msg = sProp.ProposalBytes
  1069  	sProp.Signature = sProp.ProposalBytes
  1070  	res := stub.MockInvokeWithSignedProposal("1", args, sProp)
  1071  	if res.Status != shim.OK {
  1072  		t.FailNow()
  1073  	}
  1074  
  1075  	// Should fail
  1076  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Bob"), []byte("msg1"))
  1077  	identityDeserializer.Msg = sProp.ProposalBytes
  1078  	sProp.Signature = sProp.ProposalBytes
  1079  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1080  	if res.Status == shim.OK {
  1081  		t.FailNow()
  1082  	}
  1083  }
  1084  
  1085  // TestGetChaincodesAccessRights verifies that only authorized parties can call
  1086  // the GETCHAINCODES function
  1087  func TestGetChaincodesAccessRights(t *testing.T) {
  1088  	scc := new(LifeCycleSysCC)
  1089  	stub := shim.NewMockStub("lscc", scc)
  1090  
  1091  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
  1092  		fmt.Println("Init failed", string(res.Message))
  1093  		t.FailNow()
  1094  	}
  1095  
  1096  	// Init the policy checker
  1097  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
  1098  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
  1099  		Managers: map[string]policies.Manager{
  1100  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
  1101  		},
  1102  	}
  1103  	scc.policyChecker = policy.NewPolicyChecker(
  1104  		policyManagerGetter,
  1105  		identityDeserializer,
  1106  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
  1107  	)
  1108  
  1109  	// Should pass
  1110  	args := [][]byte{[]byte(GETCHAINCODES)}
  1111  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
  1112  	identityDeserializer.Msg = sProp.ProposalBytes
  1113  	sProp.Signature = sProp.ProposalBytes
  1114  	res := stub.MockInvokeWithSignedProposal("1", args, sProp)
  1115  	if res.Status != shim.OK {
  1116  		t.FailNow()
  1117  	}
  1118  
  1119  	// Should fail
  1120  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Bob"), []byte("msg1"))
  1121  	identityDeserializer.Msg = sProp.ProposalBytes
  1122  	sProp.Signature = sProp.ProposalBytes
  1123  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1124  	if res.Status == shim.OK {
  1125  		t.FailNow()
  1126  	}
  1127  }
  1128  
  1129  // TestGetCCInfoAccessRights verifies that only authorized parties can call
  1130  // the GETCCINFO function
  1131  func TestGetCCAccessRights(t *testing.T) {
  1132  	scc := new(LifeCycleSysCC)
  1133  	stub := shim.NewMockStub("lscc", scc)
  1134  
  1135  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
  1136  		fmt.Println("Init failed", string(res.Message))
  1137  		t.FailNow()
  1138  	}
  1139  
  1140  	// Init the policy checker
  1141  	identityDeserializer := &policy.MockIdentityDeserializer{[]byte("Alice"), []byte("msg1")}
  1142  	policyManagerGetter := &policy.MockChannelPolicyManagerGetter{
  1143  		Managers: map[string]policies.Manager{
  1144  			"test": &policy.MockChannelPolicyManager{MockPolicy: &policy.MockPolicy{Deserializer: identityDeserializer}},
  1145  		},
  1146  	}
  1147  	scc.policyChecker = policy.NewPolicyChecker(
  1148  		policyManagerGetter,
  1149  		identityDeserializer,
  1150  		&policy.MockMSPPrincipalGetter{Principal: []byte("Alice")},
  1151  	)
  1152  
  1153  	cds, err := constructDeploymentSpec("example02", "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", "0", [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}, true)
  1154  
  1155  	var b []byte
  1156  	if b, err = proto.Marshal(cds); err != nil || b == nil {
  1157  		t.FailNow()
  1158  	}
  1159  
  1160  	args := [][]byte{[]byte(DEPLOY), []byte("test"), b}
  1161  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
  1162  		t.FailNow()
  1163  	}
  1164  
  1165  	//Force remove CC
  1166  	defer os.Remove(lscctestpath + "/example02.0")
  1167  
  1168  	// GETCCINFO
  1169  	// Should pass
  1170  	args = [][]byte{[]byte(GETCCINFO), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
  1171  	sProp, _ := utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
  1172  	identityDeserializer.Msg = sProp.ProposalBytes
  1173  	sProp.Signature = sProp.ProposalBytes
  1174  	res := stub.MockInvokeWithSignedProposal("1", args, sProp)
  1175  	if res.Status != shim.OK {
  1176  		t.Logf("This should pass [%s]", res.Message)
  1177  		t.FailNow()
  1178  	}
  1179  
  1180  	// Should fail
  1181  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Bob"), []byte("msg1"))
  1182  	identityDeserializer.Msg = sProp.ProposalBytes
  1183  	sProp.Signature = sProp.ProposalBytes
  1184  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1185  	if res.Status == shim.OK {
  1186  		t.Logf("This should fail [%s]", res.Message)
  1187  		t.FailNow()
  1188  	}
  1189  
  1190  	// GETDEPSPEC
  1191  	// Should pass
  1192  	args = [][]byte{[]byte(GETDEPSPEC), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
  1193  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
  1194  	identityDeserializer.Msg = sProp.ProposalBytes
  1195  	sProp.Signature = sProp.ProposalBytes
  1196  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1197  	if res.Status != shim.OK {
  1198  		t.Logf("This should pass [%s]", res.Message)
  1199  		t.FailNow()
  1200  	}
  1201  
  1202  	// Should fail
  1203  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Bob"), []byte("msg1"))
  1204  	identityDeserializer.Msg = sProp.ProposalBytes
  1205  	sProp.Signature = sProp.ProposalBytes
  1206  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1207  	if res.Status == shim.OK {
  1208  		t.Logf("This should fail [%s]", res.Message)
  1209  		t.FailNow()
  1210  	}
  1211  
  1212  	// GETCCDATA
  1213  	// Should pass
  1214  	args = [][]byte{[]byte(GETCCDATA), []byte("test"), []byte(cds.ChaincodeSpec.ChaincodeId.Name)}
  1215  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Alice"), []byte("msg1"))
  1216  	identityDeserializer.Msg = sProp.ProposalBytes
  1217  	sProp.Signature = sProp.ProposalBytes
  1218  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1219  	if res.Status != shim.OK {
  1220  		t.Logf("This should pass [%s]", res.Message)
  1221  		t.FailNow()
  1222  	}
  1223  
  1224  	// Should fail
  1225  	sProp, _ = utils.MockSignedEndorserProposalOrPanic("", &pb.ChaincodeSpec{}, []byte("Bob"), []byte("msg1"))
  1226  	identityDeserializer.Msg = sProp.ProposalBytes
  1227  	sProp.Signature = sProp.ProposalBytes
  1228  	res = stub.MockInvokeWithSignedProposal("1", args, sProp)
  1229  	if res.Status == shim.OK {
  1230  		t.Logf("This should fail [%s]", res.Message)
  1231  		t.FailNow()
  1232  	}
  1233  }
  1234  
  1235  var id msp.SigningIdentity
  1236  var sid []byte
  1237  var mspid string
  1238  var chainid string = util.GetTestChainID()
  1239  
  1240  func TestMain(m *testing.M) {
  1241  	ccprovider.SetChaincodesPath(lscctestpath)
  1242  	sysccprovider.RegisterSystemChaincodeProviderFactory(&mocksccProviderFactory{})
  1243  	var err error
  1244  
  1245  	// setup the MSP manager so that we can sign/verify
  1246  	msptesttools.LoadMSPSetupForTesting()
  1247  
  1248  	id, err = mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
  1249  	if err != nil {
  1250  		fmt.Printf("GetSigningIdentity failed with err %s", err)
  1251  		os.Exit(-1)
  1252  	}
  1253  
  1254  	sid, err = id.Serialize()
  1255  	if err != nil {
  1256  		fmt.Printf("Serialize failed with err %s", err)
  1257  		os.Exit(-1)
  1258  	}
  1259  
  1260  	// determine the MSP identifier for the first MSP in the default chain
  1261  	var msp msp.MSP
  1262  	mspMgr := mspmgmt.GetManagerForChain(chainid)
  1263  	msps, err := mspMgr.GetMSPs()
  1264  	if err != nil {
  1265  		fmt.Printf("Could not retrieve the MSPs for the chain manager, err %s", err)
  1266  		os.Exit(-1)
  1267  	}
  1268  	if len(msps) == 0 {
  1269  		fmt.Printf("At least one MSP was expected")
  1270  		os.Exit(-1)
  1271  	}
  1272  	for _, m := range msps {
  1273  		msp = m
  1274  		break
  1275  	}
  1276  	mspid, err = msp.GetIdentifier()
  1277  	if err != nil {
  1278  		fmt.Printf("Failure getting the msp identifier, err %s", err)
  1279  		os.Exit(-1)
  1280  	}
  1281  
  1282  	os.Exit(m.Run())
  1283  }