github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/core/scc/cscc/configure_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 cscc
    17  
    18  import (
    19  	"fmt"
    20  	"net"
    21  	"os"
    22  	"testing"
    23  	"time"
    24  
    25  	"github.com/golang/protobuf/proto"
    26  	configtxtest "github.com/hyperledger/fabric/common/configtx/test"
    27  	mockpolicies "github.com/hyperledger/fabric/common/mocks/policies"
    28  	"github.com/hyperledger/fabric/core/chaincode"
    29  	"github.com/hyperledger/fabric/core/chaincode/shim"
    30  	"github.com/hyperledger/fabric/core/deliverservice"
    31  	"github.com/hyperledger/fabric/core/deliverservice/blocksprovider"
    32  	"github.com/hyperledger/fabric/core/ledger/ledgermgmt"
    33  	"github.com/hyperledger/fabric/core/peer"
    34  	"github.com/hyperledger/fabric/gossip/service"
    35  	"github.com/hyperledger/fabric/msp/mgmt"
    36  	"github.com/hyperledger/fabric/msp/mgmt/testtools"
    37  	"github.com/hyperledger/fabric/peer/gossip/mcs"
    38  	"github.com/hyperledger/fabric/protos/common"
    39  	pb "github.com/hyperledger/fabric/protos/peer"
    40  	"github.com/hyperledger/fabric/protos/utils"
    41  	"github.com/spf13/viper"
    42  	"github.com/stretchr/testify/assert"
    43  	"google.golang.org/grpc"
    44  )
    45  
    46  type mockDeliveryClient struct {
    47  }
    48  
    49  // JoinChain once peer joins the chain it should need to check whenever
    50  // it has been selected as a leader and open connection to the configured
    51  // ordering service endpoint
    52  func (*mockDeliveryClient) JoinChain(chainID string, ledgerInfo blocksprovider.LedgerInfo) error {
    53  	return nil
    54  }
    55  
    56  // Stop terminates delivery service and closes the connection
    57  func (*mockDeliveryClient) Stop() {
    58  
    59  }
    60  
    61  type mockDeliveryClientFactory struct {
    62  }
    63  
    64  func (*mockDeliveryClientFactory) Service(g service.GossipService) (deliverclient.DeliverService, error) {
    65  	return &mockDeliveryClient{}, nil
    66  }
    67  
    68  func TestConfigerInit(t *testing.T) {
    69  	e := new(PeerConfiger)
    70  	stub := shim.NewMockStub("PeerConfiger", e)
    71  
    72  	if res := stub.MockInit("1", nil); res.Status != shim.OK {
    73  		fmt.Println("Init failed", string(res.Message))
    74  		t.FailNow()
    75  	}
    76  }
    77  
    78  func setupEndpoint(t *testing.T) {
    79  	peerAddress := peer.GetLocalIP()
    80  	if peerAddress == "" {
    81  		peerAddress = "0.0.0.0"
    82  	}
    83  	peerAddress = peerAddress + ":21213"
    84  	t.Logf("Local peer IP address: %s", peerAddress)
    85  	var opts []grpc.ServerOption
    86  	grpcServer := grpc.NewServer(opts...)
    87  	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
    88  		return &pb.PeerEndpoint{Id: &pb.PeerID{Name: "cscctestpeer"}, Address: peerAddress}, nil
    89  	}
    90  	ccStartupTimeout := time.Duration(30000) * time.Millisecond
    91  	pb.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(getPeerEndpoint, false, ccStartupTimeout))
    92  }
    93  
    94  func TestConfigerInvokeJoinChainMissingParams(t *testing.T) {
    95  	viper.Set("peer.fileSystemPath", "/tmp/hyperledgertest/")
    96  	os.Mkdir("/tmp/hyperledgertest", 0755)
    97  	defer os.RemoveAll("/tmp/hyperledgertest/")
    98  
    99  	e := new(PeerConfiger)
   100  	stub := shim.NewMockStub("PeerConfiger", e)
   101  
   102  	setupEndpoint(t)
   103  	// Failed path: Not enough parameters
   104  	args := [][]byte{[]byte("JoinChain")}
   105  	if res := stub.MockInvoke("1", args); res.Status == shim.OK {
   106  		t.Fatalf("cscc invoke JoinChain should have failed with invalid number of args: %v", args)
   107  	}
   108  }
   109  
   110  func TestConfigerInvokeJoinChainWrongParams(t *testing.T) {
   111  	viper.Set("peer.fileSystemPath", "/tmp/hyperledgertest/")
   112  	os.Mkdir("/tmp/hyperledgertest", 0755)
   113  	defer os.RemoveAll("/tmp/hyperledgertest/")
   114  
   115  	e := new(PeerConfiger)
   116  	stub := shim.NewMockStub("PeerConfiger", e)
   117  
   118  	setupEndpoint(t)
   119  
   120  	// Failed path: wrong parameter type
   121  	args := [][]byte{[]byte("JoinChain"), []byte("action")}
   122  	if res := stub.MockInvoke("1", args); res.Status == shim.OK {
   123  		t.Fatalf("cscc invoke JoinChain should have failed with null genesis block.  args: %v", args)
   124  	}
   125  }
   126  
   127  func TestConfigerInvokeJoinChainCorrectParams(t *testing.T) {
   128  	viper.Set("peer.fileSystemPath", "/tmp/hyperledgertest/")
   129  	os.Mkdir("/tmp/hyperledgertest", 0755)
   130  
   131  	peer.MockInitialize()
   132  	ledgermgmt.InitializeTestEnv()
   133  	defer ledgermgmt.CleanupTestEnv()
   134  	defer os.RemoveAll("/tmp/hyperledgerest/")
   135  
   136  	e := new(PeerConfiger)
   137  	stub := shim.NewMockStub("PeerConfiger", e)
   138  
   139  	setupEndpoint(t)
   140  
   141  	// Initialize gossip service
   142  	grpcServer := grpc.NewServer()
   143  	socket, err := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 13611))
   144  	assert.NoError(t, err)
   145  	go grpcServer.Serve(socket)
   146  	defer grpcServer.Stop()
   147  
   148  	msptesttools.LoadMSPSetupForTesting("../../../msp/sampleconfig")
   149  	identity, _ := mgmt.GetLocalSigningIdentityOrPanic().Serialize()
   150  	messageCryptoService := mcs.New(&mockpolicies.PolicyManagerMgmt{})
   151  	service.InitGossipServiceCustomDeliveryFactory(identity, "localhost:13611", grpcServer, &mockDeliveryClientFactory{}, messageCryptoService)
   152  
   153  	// Successful path for JoinChain
   154  	blockBytes := mockConfigBlock()
   155  	if blockBytes == nil {
   156  		t.Fatalf("cscc invoke JoinChain failed because invalid block")
   157  	}
   158  	args := [][]byte{[]byte("JoinChain"), blockBytes}
   159  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   160  		t.Fatalf("cscc invoke JoinChain failed with: %v", err)
   161  	}
   162  
   163  	// Query the configuration block
   164  	//chainID := []byte{143, 222, 22, 192, 73, 145, 76, 110, 167, 154, 118, 66, 132, 204, 113, 168}
   165  	chainID, err := getChainID(blockBytes)
   166  	if err != nil {
   167  		t.Fatalf("cscc invoke JoinChain failed with: %v", err)
   168  	}
   169  	args = [][]byte{[]byte("GetConfigBlock"), []byte(chainID)}
   170  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   171  		t.Fatalf("cscc invoke GetConfigBlock failed with: %v", err)
   172  	}
   173  
   174  	// get channels for the peer
   175  	args = [][]byte{[]byte(GetChannels)}
   176  	res := stub.MockInvoke("1", args)
   177  	if res.Status != shim.OK {
   178  		t.FailNow()
   179  	}
   180  
   181  	cqr := &pb.ChannelQueryResponse{}
   182  	err = proto.Unmarshal(res.Payload, cqr)
   183  	if err != nil {
   184  		t.FailNow()
   185  	}
   186  
   187  	// peer joined one channel so query should return an array with one channel
   188  	if len(cqr.GetChannels()) != 1 {
   189  		t.FailNow()
   190  	}
   191  }
   192  
   193  func TestConfigerInvokeUpdateConfigBlock(t *testing.T) {
   194  	e := new(PeerConfiger)
   195  	stub := shim.NewMockStub("PeerConfiger", e)
   196  
   197  	setupEndpoint(t)
   198  
   199  	// Failed path: Not enough parameters
   200  	args := [][]byte{[]byte("UpdateConfigBlock")}
   201  	if res := stub.MockInvoke("1", args); res.Status == shim.OK {
   202  		t.Fatalf("cscc invoke UpdateConfigBlock should have failed with invalid number of args: %v", args)
   203  	}
   204  
   205  	// Failed path: wrong parameter type
   206  	args = [][]byte{[]byte("UpdateConfigBlock"), []byte("action")}
   207  	if res := stub.MockInvoke("1", args); res.Status == shim.OK {
   208  		t.Fatalf("cscc invoke UpdateConfigBlock should have failed with null genesis block - args: %v", args)
   209  	}
   210  
   211  	// Successful path for JoinChain
   212  	blockBytes := mockConfigBlock()
   213  	if blockBytes == nil {
   214  		t.Fatalf("cscc invoke UpdateConfigBlock failed because invalid block")
   215  	}
   216  	args = [][]byte{[]byte("UpdateConfigBlock"), blockBytes}
   217  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   218  		t.Fatalf("cscc invoke UpdateConfigBlock failed with: %v", res.Message)
   219  	}
   220  
   221  	// Query the configuration block
   222  	//chainID := []byte{143, 222, 22, 192, 73, 145, 76, 110, 167, 154, 118, 66, 132, 204, 113, 168}
   223  	chainID, err := getChainID(blockBytes)
   224  	if err != nil {
   225  		t.Fatalf("cscc invoke UpdateConfigBlock failed with: %v", err)
   226  	}
   227  	args = [][]byte{[]byte("GetConfigBlock"), []byte(chainID)}
   228  	if res := stub.MockInvoke("1", args); res.Status != shim.OK {
   229  		t.Fatalf("cscc invoke GetConfigBlock failed with: %v", err)
   230  	}
   231  
   232  }
   233  
   234  func mockConfigBlock() []byte {
   235  	var blockBytes []byte
   236  	block, err := configtxtest.MakeGenesisBlock("mytestchainid")
   237  	if err != nil {
   238  		blockBytes = nil
   239  	} else {
   240  		blockBytes = utils.MarshalOrPanic(block)
   241  	}
   242  	return blockBytes
   243  }
   244  
   245  func getChainID(blockBytes []byte) (string, error) {
   246  	block := &common.Block{}
   247  	if err := proto.Unmarshal(blockBytes, block); err != nil {
   248  		return "", err
   249  	}
   250  	envelope := &common.Envelope{}
   251  	if err := proto.Unmarshal(block.Data.Data[0], envelope); err != nil {
   252  		return "", err
   253  	}
   254  	payload := &common.Payload{}
   255  	if err := proto.Unmarshal(envelope.Payload, payload); err != nil {
   256  		return "", err
   257  	}
   258  	chdr, err := utils.UnmarshalChannelHeader(payload.Header.ChannelHeader)
   259  	if err != nil {
   260  		return "", err
   261  	}
   262  	fmt.Printf("Channel id: %v\n", chdr.ChannelId)
   263  	return chdr.ChannelId, nil
   264  }