github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/core/endorser/endorser_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  
    17  package endorser
    18  
    19  import (
    20  	"fmt"
    21  	"io/ioutil"
    22  	"net"
    23  	"os"
    24  	"testing"
    25  	"time"
    26  
    27  	"path/filepath"
    28  
    29  	"errors"
    30  
    31  	"github.com/golang/protobuf/proto"
    32  	mockpolicies "github.com/hyperledger/fabric/common/mocks/policies"
    33  	"github.com/hyperledger/fabric/common/policies"
    34  	"github.com/hyperledger/fabric/common/util"
    35  	"github.com/hyperledger/fabric/core/chaincode"
    36  	"github.com/hyperledger/fabric/core/common/ccprovider"
    37  	"github.com/hyperledger/fabric/core/config"
    38  	"github.com/hyperledger/fabric/core/container"
    39  	"github.com/hyperledger/fabric/core/peer"
    40  	syscc "github.com/hyperledger/fabric/core/scc"
    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  	pbutils "github.com/hyperledger/fabric/protos/utils"
    47  	"github.com/spf13/viper"
    48  	"golang.org/x/net/context"
    49  	"google.golang.org/grpc"
    50  	"google.golang.org/grpc/credentials"
    51  )
    52  
    53  var endorserServer pb.EndorserServer
    54  var signer msp.SigningIdentity
    55  
    56  type testEnvironment struct {
    57  	tempDir  string
    58  	listener net.Listener
    59  }
    60  
    61  //initialize peer and start up. If security==enabled, login as vp
    62  func initPeer(chainID string) (*testEnvironment, error) {
    63  	//start clean
    64  	// finitPeer(nil)
    65  	var opts []grpc.ServerOption
    66  	if viper.GetBool("peer.tls.enabled") {
    67  		creds, err := credentials.NewServerTLSFromFile(config.GetPath("peer.tls.cert.file"), config.GetPath("peer.tls.key.file"))
    68  		if err != nil {
    69  			return nil, fmt.Errorf("Failed to generate credentials %v", err)
    70  		}
    71  		opts = []grpc.ServerOption{grpc.Creds(creds)}
    72  	}
    73  	grpcServer := grpc.NewServer(opts...)
    74  
    75  	tempDir := newTempDir()
    76  	viper.Set("peer.fileSystemPath", filepath.Join(tempDir, "hyperledger", "production"))
    77  
    78  	peerAddress, err := peer.GetLocalAddress()
    79  	if err != nil {
    80  		return nil, fmt.Errorf("Error obtaining peer address: %s", err)
    81  	}
    82  	lis, err := net.Listen("tcp", peerAddress)
    83  	if err != nil {
    84  		return nil, fmt.Errorf("Error starting peer listener %s", err)
    85  	}
    86  
    87  	//initialize ledger
    88  	peer.MockInitialize()
    89  
    90  	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
    91  		return &pb.PeerEndpoint{Id: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil
    92  	}
    93  
    94  	ccStartupTimeout := time.Duration(30000) * time.Millisecond
    95  	pb.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(getPeerEndpoint, false, ccStartupTimeout))
    96  
    97  	syscc.RegisterSysCCs()
    98  
    99  	if err = peer.MockCreateChain(chainID); err != nil {
   100  		closeListenerAndSleep(lis)
   101  		return nil, err
   102  	}
   103  
   104  	syscc.DeploySysCCs(chainID)
   105  
   106  	go grpcServer.Serve(lis)
   107  
   108  	return &testEnvironment{tempDir: tempDir, listener: lis}, nil
   109  }
   110  
   111  func finitPeer(tev *testEnvironment) {
   112  	closeListenerAndSleep(tev.listener)
   113  	os.RemoveAll(tev.tempDir)
   114  }
   115  
   116  func closeListenerAndSleep(l net.Listener) {
   117  	if l != nil {
   118  		l.Close()
   119  		time.Sleep(2 * time.Second)
   120  	}
   121  }
   122  
   123  // getInvokeProposal gets the proposal for the chaincode invocation
   124  // Currently supported only for Invokes
   125  // It returns the proposal and the transaction id associated to the proposal
   126  func getInvokeProposal(cis *pb.ChaincodeInvocationSpec, chainID string, creator []byte) (*pb.Proposal, string, error) {
   127  	return pbutils.CreateChaincodeProposal(common.HeaderType_ENDORSER_TRANSACTION, chainID, cis, creator)
   128  }
   129  
   130  // getInvokeProposalOverride allows to get a proposal for the chaincode invocation
   131  // overriding transaction id and nonce which are by default auto-generated.
   132  // It returns the proposal and the transaction id associated to the proposal
   133  func getInvokeProposalOverride(txid string, cis *pb.ChaincodeInvocationSpec, chainID string, nonce, creator []byte) (*pb.Proposal, string, error) {
   134  	return pbutils.CreateChaincodeProposalWithTxIDNonceAndTransient(txid, common.HeaderType_ENDORSER_TRANSACTION, chainID, cis, nonce, creator, nil)
   135  }
   136  
   137  func getDeployProposal(cds *pb.ChaincodeDeploymentSpec, chainID string, creator []byte) (*pb.Proposal, error) {
   138  	return getDeployOrUpgradeProposal(cds, chainID, creator, false)
   139  }
   140  
   141  func getUpgradeProposal(cds *pb.ChaincodeDeploymentSpec, chainID string, creator []byte) (*pb.Proposal, error) {
   142  	return getDeployOrUpgradeProposal(cds, chainID, creator, true)
   143  }
   144  
   145  //getDeployOrUpgradeProposal gets the proposal for the chaincode deploy or upgrade
   146  //the payload is a ChaincodeDeploymentSpec
   147  func getDeployOrUpgradeProposal(cds *pb.ChaincodeDeploymentSpec, chainID string, creator []byte, upgrade bool) (*pb.Proposal, error) {
   148  	//we need to save off the chaincode as we have to instantiate with nil CodePackage
   149  	var err error
   150  	if err = ccprovider.PutChaincodeIntoFS(cds); err != nil {
   151  		return nil, err
   152  	}
   153  
   154  	cds.CodePackage = nil
   155  
   156  	b, err := proto.Marshal(cds)
   157  	if err != nil {
   158  		return nil, err
   159  	}
   160  
   161  	var propType string
   162  	if upgrade {
   163  		propType = "upgrade"
   164  	} else {
   165  		propType = "deploy"
   166  	}
   167  	sccver := util.GetSysCCVersion()
   168  	//wrap the deployment in an invocation spec to lscc...
   169  	lsccSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: &pb.ChaincodeSpec{Type: pb.ChaincodeSpec_GOLANG, ChaincodeId: &pb.ChaincodeID{Name: "lscc", Version: sccver}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte(propType), []byte(chainID), b}}}}
   170  
   171  	//...and get the proposal for it
   172  	var prop *pb.Proposal
   173  	if prop, _, err = getInvokeProposal(lsccSpec, chainID, creator); err != nil {
   174  		return nil, err
   175  	}
   176  
   177  	return prop, nil
   178  }
   179  
   180  func getSignedProposal(prop *pb.Proposal, signer msp.SigningIdentity) (*pb.SignedProposal, error) {
   181  	propBytes, err := pbutils.GetBytesProposal(prop)
   182  	if err != nil {
   183  		return nil, err
   184  	}
   185  
   186  	signature, err := signer.Sign(propBytes)
   187  	if err != nil {
   188  		return nil, err
   189  	}
   190  
   191  	return &pb.SignedProposal{ProposalBytes: propBytes, Signature: signature}, nil
   192  }
   193  
   194  func getDeploymentSpec(context context.Context, spec *pb.ChaincodeSpec) (*pb.ChaincodeDeploymentSpec, error) {
   195  	codePackageBytes, err := container.GetChaincodePackageBytes(spec)
   196  	if err != nil {
   197  		return nil, err
   198  	}
   199  	chaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: codePackageBytes}
   200  	return chaincodeDeploymentSpec, nil
   201  }
   202  
   203  func deploy(endorserServer pb.EndorserServer, chainID string, spec *pb.ChaincodeSpec, f func(*pb.ChaincodeDeploymentSpec)) (*pb.ProposalResponse, *pb.Proposal, error) {
   204  	return deployOrUpgrade(endorserServer, chainID, spec, f, false)
   205  }
   206  
   207  func upgrade(endorserServer pb.EndorserServer, chainID string, spec *pb.ChaincodeSpec, f func(*pb.ChaincodeDeploymentSpec)) (*pb.ProposalResponse, *pb.Proposal, error) {
   208  	return deployOrUpgrade(endorserServer, chainID, spec, f, true)
   209  }
   210  
   211  func deployOrUpgrade(endorserServer pb.EndorserServer, chainID string, spec *pb.ChaincodeSpec, f func(*pb.ChaincodeDeploymentSpec), upgrade bool) (*pb.ProposalResponse, *pb.Proposal, error) {
   212  	var err error
   213  	var depSpec *pb.ChaincodeDeploymentSpec
   214  
   215  	ctxt := context.Background()
   216  	depSpec, err = getDeploymentSpec(ctxt, spec)
   217  	if err != nil {
   218  		return nil, nil, err
   219  	}
   220  
   221  	if f != nil {
   222  		f(depSpec)
   223  	}
   224  
   225  	creator, err := signer.Serialize()
   226  	if err != nil {
   227  		return nil, nil, err
   228  	}
   229  
   230  	var prop *pb.Proposal
   231  	if upgrade {
   232  		prop, err = getUpgradeProposal(depSpec, chainID, creator)
   233  	} else {
   234  		prop, err = getDeployProposal(depSpec, chainID, creator)
   235  	}
   236  	if err != nil {
   237  		return nil, nil, err
   238  	}
   239  
   240  	var signedProp *pb.SignedProposal
   241  	signedProp, err = getSignedProposal(prop, signer)
   242  	if err != nil {
   243  		return nil, nil, err
   244  	}
   245  
   246  	var resp *pb.ProposalResponse
   247  	resp, err = endorserServer.ProcessProposal(context.Background(), signedProp)
   248  
   249  	return resp, prop, err
   250  }
   251  
   252  func invoke(chainID string, spec *pb.ChaincodeSpec) (*pb.Proposal, *pb.ProposalResponse, string, []byte, error) {
   253  	invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}
   254  
   255  	creator, err := signer.Serialize()
   256  	if err != nil {
   257  		return nil, nil, "", nil, err
   258  	}
   259  
   260  	var prop *pb.Proposal
   261  	prop, txID, err := getInvokeProposal(invocation, chainID, creator)
   262  	if err != nil {
   263  		return nil, nil, "", nil, fmt.Errorf("Error creating proposal  %s: %s\n", spec.ChaincodeId, err)
   264  	}
   265  
   266  	nonce, err := pbutils.GetNonce(prop)
   267  	if err != nil {
   268  		return nil, nil, "", nil, fmt.Errorf("Failed getting nonce  %s: %s\n", spec.ChaincodeId, err)
   269  	}
   270  
   271  	var signedProp *pb.SignedProposal
   272  	signedProp, err = getSignedProposal(prop, signer)
   273  	if err != nil {
   274  		return nil, nil, "", nil, err
   275  	}
   276  
   277  	resp, err := endorserServer.ProcessProposal(context.Background(), signedProp)
   278  	if err != nil {
   279  		return nil, nil, "", nil, fmt.Errorf("Error endorsing %s: %s\n", spec.ChaincodeId, err)
   280  	}
   281  
   282  	return prop, resp, txID, nonce, err
   283  }
   284  
   285  func invokeWithOverride(txid string, chainID string, spec *pb.ChaincodeSpec, nonce []byte) (*pb.ProposalResponse, error) {
   286  	invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}
   287  
   288  	creator, err := signer.Serialize()
   289  	if err != nil {
   290  		return nil, err
   291  	}
   292  
   293  	var prop *pb.Proposal
   294  	prop, _, err = getInvokeProposalOverride(txid, invocation, chainID, nonce, creator)
   295  	if err != nil {
   296  		return nil, fmt.Errorf("Error creating proposal with override  %s %s: %s\n", txid, spec.ChaincodeId, err)
   297  	}
   298  
   299  	var signedProp *pb.SignedProposal
   300  	signedProp, err = getSignedProposal(prop, signer)
   301  	if err != nil {
   302  		return nil, err
   303  	}
   304  
   305  	resp, err := endorserServer.ProcessProposal(context.Background(), signedProp)
   306  	if err != nil {
   307  		return nil, fmt.Errorf("Error endorsing %s %s: %s\n", txid, spec.ChaincodeId, err)
   308  	}
   309  
   310  	return resp, err
   311  }
   312  
   313  func deleteChaincodeOnDisk(chaincodeID string) {
   314  	os.RemoveAll(filepath.Join(config.GetPath("peer.fileSystemPath"), "chaincodes", chaincodeID))
   315  }
   316  
   317  //begin tests. Note that we rely upon the system chaincode and peer to be created
   318  //once and be used for all the tests. In order to avoid dependencies / collisions
   319  //due to deployed chaincodes, trying to use different chaincodes for different
   320  //tests
   321  
   322  //TestDeploy deploy chaincode example01
   323  func TestDeploy(t *testing.T) {
   324  	chainID := util.GetTestChainID()
   325  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: &pb.ChaincodeID{Name: "ex01", Path: "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01", Version: "0"}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}}}
   326  	defer deleteChaincodeOnDisk("ex01.0")
   327  
   328  	cccid := ccprovider.NewCCContext(chainID, "ex01", "0", "", false, nil, nil)
   329  
   330  	_, _, err := deploy(endorserServer, chainID, spec, nil)
   331  	if err != nil {
   332  		t.Fail()
   333  		t.Logf("Deploy-error in deploy %s", err)
   334  		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
   335  		return
   336  	}
   337  	chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
   338  }
   339  
   340  //TestRedeploy - deploy two times, second time should fail but example02 should remain deployed
   341  func TestRedeploy(t *testing.T) {
   342  	chainID := util.GetTestChainID()
   343  
   344  	//invalid arguments
   345  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: &pb.ChaincodeID{Name: "ex02", Path: "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02", Version: "0"}, Input: &pb.ChaincodeInput{Args: [][]byte{[]byte("init"), []byte("a"), []byte("100"), []byte("b"), []byte("200")}}}
   346  
   347  	defer deleteChaincodeOnDisk("ex02.0")
   348  
   349  	cccid := ccprovider.NewCCContext(chainID, "ex02", "0", "", false, nil, nil)
   350  
   351  	_, _, err := deploy(endorserServer, chainID, spec, nil)
   352  	if err != nil {
   353  		t.Fail()
   354  		t.Logf("error in endorserServer.ProcessProposal %s", err)
   355  		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
   356  		return
   357  	}
   358  
   359  	deleteChaincodeOnDisk("ex02.0")
   360  
   361  	//second time should not fail as we are just simulating
   362  	_, _, err = deploy(endorserServer, chainID, spec, nil)
   363  	if err != nil {
   364  		t.Fail()
   365  		t.Logf("error in endorserServer.ProcessProposal %s", err)
   366  		chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
   367  		return
   368  	}
   369  	chaincode.GetChain().Stop(context.Background(), cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: spec})
   370  }
   371  
   372  // TestDeployAndInvoke deploys and invokes chaincode_example01
   373  func TestDeployAndInvoke(t *testing.T) {
   374  	chainID := util.GetTestChainID()
   375  	var ctxt = context.Background()
   376  
   377  	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
   378  	chaincodeID := &pb.ChaincodeID{Path: url, Name: "ex01", Version: "0"}
   379  
   380  	defer deleteChaincodeOnDisk("ex01.0")
   381  
   382  	args := []string{"10"}
   383  
   384  	f := "init"
   385  	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
   386  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: argsDeploy}}
   387  
   388  	cccid := ccprovider.NewCCContext(chainID, "ex01", "0", "", false, nil, nil)
   389  
   390  	resp, prop, err := deploy(endorserServer, chainID, spec, nil)
   391  	chaincodeID1 := spec.ChaincodeId.Name
   392  	if err != nil {
   393  		t.Fail()
   394  		t.Logf("Error deploying <%s>: %s", chaincodeID1, err)
   395  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   396  		return
   397  	}
   398  	var nextBlockNumber uint64 = 1 // first block needs to be block number = 1. Genesis block is block 0
   399  	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
   400  	if err != nil {
   401  		t.Fail()
   402  		t.Logf("Error committing deploy <%s>: %s", chaincodeID1, err)
   403  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   404  		return
   405  	}
   406  
   407  	f = "invoke"
   408  	invokeArgs := append([]string{f}, args...)
   409  	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
   410  	prop, resp, txid, nonce, err := invoke(chainID, spec)
   411  	if err != nil {
   412  		t.Fail()
   413  		t.Logf("Error invoking transaction: %s", err)
   414  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   415  		return
   416  	}
   417  	// Commit invoke
   418  	nextBlockNumber++
   419  	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
   420  	if err != nil {
   421  		t.Fail()
   422  		t.Logf("Error committing first invoke <%s>: %s", chaincodeID1, err)
   423  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   424  		return
   425  	}
   426  
   427  	// Now test for an invalid TxID
   428  	f = "invoke"
   429  	invokeArgs = append([]string{f}, args...)
   430  	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
   431  	_, err = invokeWithOverride("invalid_tx_id", chainID, spec, nonce)
   432  	if err == nil {
   433  		t.Fail()
   434  		t.Log("Replay attack protection faild. Transaction with invalid txid passed")
   435  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   436  		return
   437  	}
   438  
   439  	// Now test for duplicated TxID
   440  	f = "invoke"
   441  	invokeArgs = append([]string{f}, args...)
   442  	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
   443  	_, err = invokeWithOverride(txid, chainID, spec, nonce)
   444  	if err == nil {
   445  		t.Fail()
   446  		t.Log("Replay attack protection faild. Transaction with duplicaged txid passed")
   447  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   448  		return
   449  	}
   450  
   451  	fmt.Printf("Invoke test passed\n")
   452  	t.Logf("Invoke test passed")
   453  
   454  	chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   455  }
   456  
   457  // TestUpgradeAndInvoke deploys chaincode_example01, upgrade it with chaincode_example02, then invoke it
   458  func TestDeployAndUpgrade(t *testing.T) {
   459  	chainID := util.GetTestChainID()
   460  	var ctxt = context.Background()
   461  
   462  	url1 := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
   463  	url2 := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
   464  	chaincodeID1 := &pb.ChaincodeID{Path: url1, Name: "upgradeex01", Version: "0"}
   465  	chaincodeID2 := &pb.ChaincodeID{Path: url2, Name: "upgradeex01", Version: "1"}
   466  
   467  	defer deleteChaincodeOnDisk("upgradeex01.0")
   468  	defer deleteChaincodeOnDisk("upgradeex01.1")
   469  
   470  	f := "init"
   471  	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
   472  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID1, Input: &pb.ChaincodeInput{Args: argsDeploy}}
   473  
   474  	cccid1 := ccprovider.NewCCContext(chainID, "upgradeex01", "0", "", false, nil, nil)
   475  	cccid2 := ccprovider.NewCCContext(chainID, "upgradeex01", "1", "", false, nil, nil)
   476  
   477  	resp, prop, err := deploy(endorserServer, chainID, spec, nil)
   478  
   479  	chaincodeName := spec.ChaincodeId.Name
   480  	if err != nil {
   481  		t.Fail()
   482  		chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
   483  		chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
   484  		t.Logf("Error deploying <%s>: %s", chaincodeName, err)
   485  		return
   486  	}
   487  
   488  	var nextBlockNumber uint64 = 3 // something above created block 0
   489  	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
   490  	if err != nil {
   491  		t.Fail()
   492  		chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
   493  		chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
   494  		t.Logf("Error committing <%s>: %s", chaincodeName, err)
   495  		return
   496  	}
   497  
   498  	argsUpgrade := util.ToChaincodeArgs(f, "a", "150", "b", "300")
   499  	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID2, Input: &pb.ChaincodeInput{Args: argsUpgrade}}
   500  	_, _, err = upgrade(endorserServer, chainID, spec, nil)
   501  	if err != nil {
   502  		t.Fail()
   503  		chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
   504  		chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
   505  		t.Logf("Error upgrading <%s>: %s", chaincodeName, err)
   506  		return
   507  	}
   508  
   509  	fmt.Printf("Upgrade test passed\n")
   510  	t.Logf("Upgrade test passed")
   511  
   512  	chaincode.GetChain().Stop(ctxt, cccid1, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID1}})
   513  	chaincode.GetChain().Stop(ctxt, cccid2, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID2}})
   514  }
   515  
   516  // TestWritersACLFail deploys a chaincode and then tries to invoke it;
   517  // however we inject a special policy for writers to simulate
   518  // the scenario in which the creator of this proposal is not among
   519  // the writers for the chain
   520  func TestWritersACLFail(t *testing.T) {
   521  	//skip pending FAB-2457 fix
   522  	t.Skip()
   523  	chainID := util.GetTestChainID()
   524  	var ctxt = context.Background()
   525  
   526  	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
   527  	chaincodeID := &pb.ChaincodeID{Path: url, Name: "ex01-fail", Version: "0"}
   528  
   529  	defer deleteChaincodeOnDisk("ex01-fail.0")
   530  
   531  	args := []string{"10"}
   532  
   533  	f := "init"
   534  	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
   535  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: argsDeploy}}
   536  
   537  	cccid := ccprovider.NewCCContext(chainID, "ex01-fail", "0", "", false, nil, nil)
   538  
   539  	resp, prop, err := deploy(endorserServer, chainID, spec, nil)
   540  	chaincodeID1 := spec.ChaincodeId.Name
   541  	if err != nil {
   542  		t.Fail()
   543  		t.Logf("Error deploying <%s>: %s", chaincodeID1, err)
   544  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   545  		return
   546  	}
   547  	var nextBlockNumber uint64 = 3 // The tests that ran before this test created blocks 0-2
   548  	err = endorserServer.(*Endorser).commitTxSimulation(prop, chainID, signer, resp, nextBlockNumber)
   549  	if err != nil {
   550  		t.Fail()
   551  		t.Logf("Error committing deploy <%s>: %s", chaincodeID1, err)
   552  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   553  		return
   554  	}
   555  
   556  	// here we inject a reject policy for writers
   557  	// to simulate the scenario in which the invoker
   558  	// is not authorized to issue this proposal
   559  	rejectpolicy := &mockpolicies.Policy{
   560  		Err: errors.New("The creator of this proposal does not fulfil the writers policy of this chain"),
   561  	}
   562  	pm := peer.GetPolicyManager(chainID)
   563  	pm.(*mockpolicies.Manager).PolicyMap = map[string]policies.Policy{policies.ChannelApplicationWriters: rejectpolicy}
   564  
   565  	f = "invoke"
   566  	invokeArgs := append([]string{f}, args...)
   567  	spec = &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: util.ToChaincodeArgs(invokeArgs...)}}
   568  	prop, resp, _, _, err = invoke(chainID, spec)
   569  	if err == nil {
   570  		t.Fail()
   571  		t.Logf("Invocation should have failed")
   572  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   573  		return
   574  	}
   575  
   576  	fmt.Println("TestWritersACLFail passed")
   577  	t.Logf("TestWritersACLFail passed")
   578  
   579  	chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   580  }
   581  
   582  // TestAdminACLFail deploys tried to deploy a chaincode;
   583  // however we inject a special policy for admins to simulate
   584  // the scenario in which the creator of this proposal is not among
   585  // the admins for the chain
   586  func TestAdminACLFail(t *testing.T) {
   587  	//skip pending FAB-2457 fix
   588  	t.Skip()
   589  	chainID := util.GetTestChainID()
   590  
   591  	// here we inject a reject policy for admins
   592  	// to simulate the scenario in which the invoker
   593  	// is not authorized to issue this proposal
   594  	rejectpolicy := &mockpolicies.Policy{
   595  		Err: errors.New("The creator of this proposal does not fulfil the writers policy of this chain"),
   596  	}
   597  	pm := peer.GetPolicyManager(chainID)
   598  	pm.(*mockpolicies.Manager).PolicyMap = map[string]policies.Policy{policies.ChannelApplicationAdmins: rejectpolicy}
   599  
   600  	var ctxt = context.Background()
   601  
   602  	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example01"
   603  	chaincodeID := &pb.ChaincodeID{Path: url, Name: "ex01-fail1", Version: "0"}
   604  
   605  	defer deleteChaincodeOnDisk("ex01-fail1.0")
   606  
   607  	f := "init"
   608  	argsDeploy := util.ToChaincodeArgs(f, "a", "100", "b", "200")
   609  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: argsDeploy}}
   610  
   611  	cccid := ccprovider.NewCCContext(chainID, "ex01-fail1", "0", "", false, nil, nil)
   612  
   613  	_, _, err := deploy(endorserServer, chainID, spec, nil)
   614  	if err == nil {
   615  		t.Fail()
   616  		t.Logf("Deploying chaincode should have failed!")
   617  		chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   618  		return
   619  	}
   620  
   621  	fmt.Println("TestAdminACLFail passed")
   622  	t.Logf("TestATestAdminACLFailCLFail passed")
   623  
   624  	chaincode.GetChain().Stop(ctxt, cccid, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeId: chaincodeID}})
   625  }
   626  
   627  // TestInvokeSccFail makes sure that invoking a system chaincode fails
   628  func TestInvokeSccFail(t *testing.T) {
   629  	chainID := util.GetTestChainID()
   630  
   631  	chaincodeID := &pb.ChaincodeID{Name: "escc"}
   632  	args := util.ToChaincodeArgs("someFunc", "someArg")
   633  	spec := &pb.ChaincodeSpec{Type: 1, ChaincodeId: chaincodeID, Input: &pb.ChaincodeInput{Args: args}}
   634  	_, _, _, _, err := invoke(chainID, spec)
   635  	if err == nil {
   636  		t.Logf("Invoking escc should have failed!")
   637  		t.Fail()
   638  		return
   639  	}
   640  }
   641  
   642  func newTempDir() string {
   643  	tempDir, err := ioutil.TempDir("", "fabric-")
   644  	if err != nil {
   645  		panic(err)
   646  	}
   647  	return tempDir
   648  }
   649  
   650  func TestMain(m *testing.M) {
   651  	SetupTestConfig()
   652  
   653  	chainID := util.GetTestChainID()
   654  	tev, err := initPeer(chainID)
   655  	if err != nil {
   656  		os.Exit(-1)
   657  		fmt.Printf("Could not initialize tests")
   658  		finitPeer(tev)
   659  		return
   660  	}
   661  
   662  	endorserServer = NewEndorserServer()
   663  
   664  	// setup the MSP manager so that we can sign/verify
   665  	err = msptesttools.LoadMSPSetupForTesting()
   666  	if err != nil {
   667  		fmt.Printf("Could not initialize msp/signer, err %s", err)
   668  		finitPeer(tev)
   669  		os.Exit(-1)
   670  		return
   671  	}
   672  	signer, err = mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
   673  	if err != nil {
   674  		fmt.Printf("Could not initialize msp/signer")
   675  		finitPeer(tev)
   676  		os.Exit(-1)
   677  		return
   678  	}
   679  
   680  	retVal := m.Run()
   681  
   682  	finitPeer(tev)
   683  
   684  	os.Exit(retVal)
   685  }