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