github.com/true-sqn/fabric@v2.1.1+incompatible/core/peer/peer_test.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package peer 8 9 import ( 10 "fmt" 11 "io/ioutil" 12 "math/rand" 13 "os" 14 "path/filepath" 15 "runtime" 16 "testing" 17 18 "github.com/hyperledger/fabric-protos-go/common" 19 "github.com/hyperledger/fabric/bccsp/sw" 20 configtxtest "github.com/hyperledger/fabric/common/configtx/test" 21 "github.com/hyperledger/fabric/common/metrics/disabled" 22 "github.com/hyperledger/fabric/core/committer/txvalidator/plugin" 23 "github.com/hyperledger/fabric/core/deliverservice" 24 validation "github.com/hyperledger/fabric/core/handlers/validation/api" 25 "github.com/hyperledger/fabric/core/ledger" 26 "github.com/hyperledger/fabric/core/ledger/ledgermgmt" 27 "github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledgermgmttest" 28 "github.com/hyperledger/fabric/core/ledger/mock" 29 ledgermocks "github.com/hyperledger/fabric/core/ledger/mock" 30 "github.com/hyperledger/fabric/core/transientstore" 31 "github.com/hyperledger/fabric/gossip/gossip" 32 gossipmetrics "github.com/hyperledger/fabric/gossip/metrics" 33 "github.com/hyperledger/fabric/gossip/privdata" 34 "github.com/hyperledger/fabric/gossip/service" 35 gossipservice "github.com/hyperledger/fabric/gossip/service" 36 peergossip "github.com/hyperledger/fabric/internal/peer/gossip" 37 "github.com/hyperledger/fabric/internal/peer/gossip/mocks" 38 "github.com/hyperledger/fabric/internal/pkg/comm" 39 "github.com/hyperledger/fabric/msp/mgmt" 40 msptesttools "github.com/hyperledger/fabric/msp/mgmt/testtools" 41 "github.com/stretchr/testify/assert" 42 "github.com/stretchr/testify/require" 43 "google.golang.org/grpc" 44 ) 45 46 func TestMain(m *testing.M) { 47 msptesttools.LoadMSPSetupForTesting() 48 rc := m.Run() 49 os.Exit(rc) 50 } 51 52 func NewTestPeer(t *testing.T) (*Peer, func()) { 53 tempdir, err := ioutil.TempDir("", "peer-test") 54 require.NoError(t, err, "failed to create temporary directory") 55 56 // Initialize gossip service 57 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore()) 58 assert.NoError(t, err) 59 signer := mgmt.GetLocalSigningIdentityOrPanic(cryptoProvider) 60 61 messageCryptoService := peergossip.NewMCS(&mocks.ChannelPolicyManagerGetter{}, signer, mgmt.NewDeserializersManager(cryptoProvider), cryptoProvider) 62 secAdv := peergossip.NewSecurityAdvisor(mgmt.NewDeserializersManager(cryptoProvider)) 63 defaultSecureDialOpts := func() []grpc.DialOption { return []grpc.DialOption{grpc.WithInsecure()} } 64 defaultDeliverClientDialOpts := []grpc.DialOption{grpc.WithBlock()} 65 defaultDeliverClientDialOpts = append( 66 defaultDeliverClientDialOpts, 67 grpc.WithDefaultCallOptions( 68 grpc.MaxCallRecvMsgSize(comm.MaxRecvMsgSize), 69 grpc.MaxCallSendMsgSize(comm.MaxSendMsgSize))) 70 defaultDeliverClientDialOpts = append( 71 defaultDeliverClientDialOpts, 72 comm.ClientKeepaliveOptions(comm.DefaultKeepaliveOptions)..., 73 ) 74 gossipConfig, err := gossip.GlobalConfig("localhost:0", nil) 75 76 gossipService, err := gossipservice.New( 77 signer, 78 gossipmetrics.NewGossipMetrics(&disabled.Provider{}), 79 "localhost:0", 80 grpc.NewServer(), 81 messageCryptoService, 82 secAdv, 83 defaultSecureDialOpts, 84 nil, 85 nil, 86 gossipConfig, 87 &service.ServiceConfig{}, 88 &privdata.PrivdataConfig{}, 89 &deliverservice.DeliverServiceConfig{ 90 ReConnectBackoffThreshold: deliverservice.DefaultReConnectBackoffThreshold, 91 ReconnectTotalTimeThreshold: deliverservice.DefaultReConnectTotalTimeThreshold, 92 }, 93 ) 94 require.NoError(t, err, "failed to create gossip service") 95 96 ledgerMgr, err := constructLedgerMgrWithTestDefaults(filepath.Join(tempdir, "ledgersData")) 97 require.NoError(t, err, "failed to create ledger manager") 98 99 assert.NoError(t, err) 100 transientStoreProvider, err := transientstore.NewStoreProvider( 101 filepath.Join(tempdir, "transientstore"), 102 ) 103 assert.NoError(t, err) 104 peerInstance := &Peer{ 105 GossipService: gossipService, 106 StoreProvider: transientStoreProvider, 107 LedgerMgr: ledgerMgr, 108 CryptoProvider: cryptoProvider, 109 } 110 111 cleanup := func() { 112 ledgerMgr.Close() 113 os.RemoveAll(tempdir) 114 } 115 return peerInstance, cleanup 116 } 117 118 func TestInitialize(t *testing.T) { 119 peerInstance, cleanup := NewTestPeer(t) 120 defer cleanup() 121 122 org1CA, err := ioutil.ReadFile(filepath.Join("testdata", "Org1-cert.pem")) 123 require.NoError(t, err) 124 org1Server1Key, err := ioutil.ReadFile(filepath.Join("testdata", "Org1-server1-key.pem")) 125 require.NoError(t, err) 126 org1Server1Cert, err := ioutil.ReadFile(filepath.Join("testdata", "Org1-server1-cert.pem")) 127 require.NoError(t, err) 128 serverConfig := comm.ServerConfig{ 129 SecOpts: comm.SecureOptions{ 130 UseTLS: true, 131 Certificate: org1Server1Cert, 132 Key: org1Server1Key, 133 ServerRootCAs: [][]byte{org1CA}, 134 RequireClientCert: true, 135 }, 136 } 137 138 server, err := comm.NewGRPCServer("localhost:0", serverConfig) 139 if err != nil { 140 t.Fatalf("NewGRPCServer failed with error [%s]", err) 141 return 142 } 143 144 peerInstance.Initialize( 145 nil, 146 server, 147 plugin.MapBasedMapper(map[string]validation.PluginFactory{}), 148 &ledgermocks.DeployedChaincodeInfoProvider{}, 149 nil, 150 nil, 151 runtime.NumCPU(), 152 ) 153 assert.Equal(t, peerInstance.server, server) 154 } 155 156 func TestCreateChannel(t *testing.T) { 157 peerInstance, cleanup := NewTestPeer(t) 158 defer cleanup() 159 160 var initArg string 161 peerInstance.Initialize( 162 func(cid string) { initArg = cid }, 163 nil, 164 plugin.MapBasedMapper(map[string]validation.PluginFactory{}), 165 &ledgermocks.DeployedChaincodeInfoProvider{}, 166 nil, 167 nil, 168 runtime.NumCPU(), 169 ) 170 171 testChainID := fmt.Sprintf("mytestchainid-%d", rand.Int()) 172 block, err := configtxtest.MakeGenesisBlock(testChainID) 173 if err != nil { 174 fmt.Printf("Failed to create a config block, err %s\n", err) 175 t.FailNow() 176 } 177 178 err = peerInstance.CreateChannel(testChainID, block, &mock.DeployedChaincodeInfoProvider{}, nil, nil) 179 if err != nil { 180 t.Fatalf("failed to create chain %s", err) 181 } 182 183 assert.Equal(t, testChainID, initArg) 184 185 // Correct ledger 186 ledger := peerInstance.GetLedger(testChainID) 187 if ledger == nil { 188 t.Fatalf("failed to get correct ledger") 189 } 190 191 // Get config block from ledger 192 block, err = ConfigBlockFromLedger(ledger) 193 assert.NoError(t, err, "Failed to get config block from ledger") 194 assert.NotNil(t, block, "Config block should not be nil") 195 assert.Equal(t, uint64(0), block.Header.Number, "config block should have been block 0") 196 197 // Bad ledger 198 ledger = peerInstance.GetLedger("BogusChain") 199 if ledger != nil { 200 t.Fatalf("got a bogus ledger") 201 } 202 203 // Correct PolicyManager 204 pmgr := peerInstance.GetPolicyManager(testChainID) 205 if pmgr == nil { 206 t.Fatal("failed to get PolicyManager") 207 } 208 209 // Bad PolicyManager 210 pmgr = peerInstance.GetPolicyManager("BogusChain") 211 if pmgr != nil { 212 t.Fatal("got a bogus PolicyManager") 213 } 214 215 channels := peerInstance.GetChannelsInfo() 216 if len(channels) != 1 { 217 t.Fatalf("incorrect number of channels") 218 } 219 } 220 221 func TestDeliverSupportManager(t *testing.T) { 222 peerInstance, cleanup := NewTestPeer(t) 223 defer cleanup() 224 225 manager := &DeliverChainManager{Peer: peerInstance} 226 227 chainSupport := manager.GetChain("fake") 228 assert.Nil(t, chainSupport, "chain support should be nil") 229 230 peerInstance.channels = map[string]*Channel{"testchain": {}} 231 chainSupport = manager.GetChain("testchain") 232 assert.NotNil(t, chainSupport, "chain support should not be nil") 233 } 234 235 func constructLedgerMgrWithTestDefaults(ledgersDataDir string) (*ledgermgmt.LedgerMgr, error) { 236 ledgerInitializer := ledgermgmttest.NewInitializer(ledgersDataDir) 237 238 ledgerInitializer.CustomTxProcessors = map[common.HeaderType]ledger.CustomTxProcessor{ 239 common.HeaderType_CONFIG: &ConfigTxProcessor{}, 240 } 241 ledgerInitializer.Config.HistoryDBConfig = &ledger.HistoryDBConfig{ 242 Enabled: true, 243 } 244 return ledgermgmt.NewLedgerMgr(ledgerInitializer), nil 245 } 246 247 // SetServer sets the gRPC server for the peer. 248 // It should only be used in peer/pkg_test. 249 func (p *Peer) SetServer(server *comm.GRPCServer) { 250 p.server = server 251 }