forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
522 lines (450 loc) · 16.1 KB
/
peer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package peer
import (
"fmt"
"sync"
"github.com/hyperledger/fabric-protos-go/common"
pb "github.com/hyperledger/fabric-protos-go/peer"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/common/channelconfig"
cc "github.com/hyperledger/fabric/common/config"
"github.com/hyperledger/fabric/common/configtx"
"github.com/hyperledger/fabric/common/deliver"
"github.com/hyperledger/fabric/common/flogging"
commonledger "github.com/hyperledger/fabric/common/ledger"
"github.com/hyperledger/fabric/common/policies"
"github.com/hyperledger/fabric/common/semaphore"
"github.com/hyperledger/fabric/core/committer"
"github.com/hyperledger/fabric/core/committer/txvalidator"
"github.com/hyperledger/fabric/core/committer/txvalidator/plugin"
validatorv14 "github.com/hyperledger/fabric/core/committer/txvalidator/v14"
validatorv20 "github.com/hyperledger/fabric/core/committer/txvalidator/v20"
"github.com/hyperledger/fabric/core/committer/txvalidator/v20/plugindispatcher"
vir "github.com/hyperledger/fabric/core/committer/txvalidator/v20/valinforetriever"
"github.com/hyperledger/fabric/core/common/privdata"
validation "github.com/hyperledger/fabric/core/handlers/validation/api/state"
"github.com/hyperledger/fabric/core/ledger"
"github.com/hyperledger/fabric/core/ledger/ledgermgmt"
"github.com/hyperledger/fabric/core/transientstore"
"github.com/hyperledger/fabric/gossip/api"
gossipprivdata "github.com/hyperledger/fabric/gossip/privdata"
gossipservice "github.com/hyperledger/fabric/gossip/service"
"github.com/hyperledger/fabric/internal/pkg/comm"
"github.com/hyperledger/fabric/internal/pkg/peer/orderers"
"github.com/hyperledger/fabric/msp"
mspmgmt "github.com/hyperledger/fabric/msp/mgmt"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
)
var peerLogger = flogging.MustGetLogger("peer")
type CollectionInfoShim struct {
plugindispatcher.CollectionAndLifecycleResources
ChannelID string
}
func (cis *CollectionInfoShim) CollectionValidationInfo(chaincodeName, collectionName string, validationState validation.State) ([]byte, error, error) {
return cis.CollectionAndLifecycleResources.CollectionValidationInfo(cis.ChannelID, chaincodeName, collectionName, validationState)
}
type gossipSupport struct {
channelconfig.Application
configtx.Validator
channelconfig.Channel
}
func ConfigBlockFromLedger(ledger ledger.PeerLedger) (*common.Block, error) {
peerLogger.Debugf("Getting config block")
// get last block. Last block number is Height-1
blockchainInfo, err := ledger.GetBlockchainInfo()
if err != nil {
return nil, err
}
lastBlock, err := ledger.GetBlockByNumber(blockchainInfo.Height - 1)
if err != nil {
return nil, err
}
// get most recent config block location from last block metadata
configBlockIndex, err := protoutil.GetLastConfigIndexFromBlock(lastBlock)
if err != nil {
return nil, err
}
// get most recent config block
configBlock, err := ledger.GetBlockByNumber(configBlockIndex)
if err != nil {
return nil, err
}
peerLogger.Debugf("Got config block[%d]", configBlockIndex)
return configBlock, nil
}
// updates the trusted roots for the peer based on updates to channels
func (p *Peer) updateTrustedRoots(cm channelconfig.Resources) {
if !p.ServerConfig.SecOpts.UseTLS {
return
}
// this is triggered on per channel basis so first update the roots for the channel
peerLogger.Debugf("Updating trusted root authorities for channel %s", cm.ConfigtxValidator().ChannelID())
p.CredentialSupport.BuildTrustedRootsForChain(cm)
// now iterate over all roots for all app and orderer channels
var trustedRoots [][]byte
for _, roots := range p.CredentialSupport.AppRootCAsByChain() {
trustedRoots = append(trustedRoots, roots...)
}
trustedRoots = append(trustedRoots, p.ServerConfig.SecOpts.ClientRootCAs...)
trustedRoots = append(trustedRoots, p.ServerConfig.SecOpts.ServerRootCAs...)
// now update the client roots for the peerServer
err := p.server.SetClientRootCAs(trustedRoots)
if err != nil {
msg := "Failed to update trusted roots from latest config block. " +
"This peer may not be able to communicate with members of channel %s (%s)"
peerLogger.Warningf(msg, cm.ConfigtxValidator().ChannelID(), err)
}
}
//
// Deliver service support structs for the peer
//
// DeliverChainManager provides access to a channel for performing deliver
type DeliverChainManager struct {
Peer *Peer
}
func (d DeliverChainManager) GetChain(chainID string) deliver.Chain {
if channel := d.Peer.Channel(chainID); channel != nil {
return channel
}
return nil
}
// fileLedgerBlockStore implements the interface expected by
// common/ledger/blockledger/file to interact with a file ledger for deliver
type fileLedgerBlockStore struct {
ledger.PeerLedger
}
func (flbs fileLedgerBlockStore) AddBlock(*common.Block) error {
return nil
}
func (flbs fileLedgerBlockStore) RetrieveBlocks(startBlockNumber uint64) (commonledger.ResultsIterator, error) {
return flbs.GetBlocksIterator(startBlockNumber)
}
// NewConfigSupport returns
func NewConfigSupport(peer *Peer) cc.Manager {
return &configSupport{
peer: peer,
}
}
type configSupport struct {
peer *Peer
}
// GetChannelConfig returns an instance of a object that represents
// current channel configuration tree of the specified channel. The
// ConfigProto method of the returned object can be used to get the
// proto representing the channel configuration.
func (c *configSupport) GetChannelConfig(cid string) cc.Config {
channel := c.peer.Channel(cid)
if channel == nil {
peerLogger.Errorf("[channel %s] channel not associated with this peer", cid)
return nil
}
return channel.Resources().ConfigtxValidator()
}
// A Peer holds references to subsystems and channels associated with a Fabric peer.
type Peer struct {
ServerConfig comm.ServerConfig
CredentialSupport *comm.CredentialSupport
StoreProvider transientstore.StoreProvider
GossipService *gossipservice.GossipService
LedgerMgr *ledgermgmt.LedgerMgr
OrdererEndpointOverrides map[string]*orderers.Endpoint
CryptoProvider bccsp.BCCSP
// validationWorkersSemaphore is used to limit the number of concurrent validation
// go routines.
validationWorkersSemaphore semaphore.Semaphore
server *comm.GRPCServer
pluginMapper plugin.Mapper
channelInitializer func(cid string)
// channels is a map of channelID to channel
mutex sync.RWMutex
channels map[string]*Channel
}
func (p *Peer) openStore(cid string) (*transientstore.Store, error) {
store, err := p.StoreProvider.OpenStore(cid)
if err != nil {
return nil, err
}
return store, nil
}
func (p *Peer) CreateChannel(
cid string,
cb *common.Block,
deployedCCInfoProvider ledger.DeployedChaincodeInfoProvider,
legacyLifecycleValidation plugindispatcher.LifecycleResources,
newLifecycleValidation plugindispatcher.CollectionAndLifecycleResources,
) error {
l, err := p.LedgerMgr.CreateLedger(cid, cb)
if err != nil {
return errors.WithMessage(err, "cannot create ledger from genesis block")
}
if err := p.createChannel(cid, l, deployedCCInfoProvider, legacyLifecycleValidation, newLifecycleValidation); err != nil {
return err
}
p.initChannel(cid)
return nil
}
// retrievePersistedChannelConfig retrieves the persisted channel config from statedb
func retrievePersistedChannelConfig(ledger ledger.PeerLedger) (*common.Config, error) {
qe, err := ledger.NewQueryExecutor()
if err != nil {
return nil, err
}
defer qe.Done()
return retrieveChannelConfig(qe)
}
// createChannel creates a new channel object and insert it into the channels slice.
func (p *Peer) createChannel(
cid string,
l ledger.PeerLedger,
deployedCCInfoProvider ledger.DeployedChaincodeInfoProvider,
legacyLifecycleValidation plugindispatcher.LifecycleResources,
newLifecycleValidation plugindispatcher.CollectionAndLifecycleResources,
) error {
chanConf, err := retrievePersistedChannelConfig(l)
if err != nil {
return err
}
bundle, err := channelconfig.NewBundle(cid, chanConf, p.CryptoProvider)
if err != nil {
return err
}
capabilitiesSupportedOrPanic(bundle)
channelconfig.LogSanityChecks(bundle)
gossipEventer := p.GossipService.NewConfigEventer()
gossipCallbackWrapper := func(bundle *channelconfig.Bundle) {
ac, ok := bundle.ApplicationConfig()
if !ok {
// TODO, handle a missing ApplicationConfig more gracefully
ac = nil
}
gossipEventer.ProcessConfigUpdate(&gossipSupport{
Validator: bundle.ConfigtxValidator(),
Application: ac,
Channel: bundle.ChannelConfig(),
})
p.GossipService.SuspectPeers(func(identity api.PeerIdentityType) bool {
// TODO: this is a place-holder that would somehow make the MSP layer suspect
// that a given certificate is revoked, or its intermediate CA is revoked.
// In the meantime, before we have such an ability, we return true in order
// to suspect ALL identities in order to validate all of them.
return true
})
}
trustedRootsCallbackWrapper := func(bundle *channelconfig.Bundle) {
p.updateTrustedRoots(bundle)
}
mspCallback := func(bundle *channelconfig.Bundle) {
// TODO remove once all references to mspmgmt are gone from peer code
mspmgmt.XXXSetMSPManager(cid, bundle.MSPManager())
}
osLogger := flogging.MustGetLogger("peer.orderers")
namedOSLogger := osLogger.With("channel", cid)
ordererSource := orderers.NewConnectionSource(namedOSLogger, p.OrdererEndpointOverrides)
ordererSourceCallback := func(bundle *channelconfig.Bundle) {
globalAddresses := bundle.ChannelConfig().OrdererAddresses()
orgAddresses := map[string]orderers.OrdererOrg{}
if ordererConfig, ok := bundle.OrdererConfig(); ok {
for orgName, org := range ordererConfig.Organizations() {
certs := [][]byte{}
for _, root := range org.MSP().GetTLSRootCerts() {
certs = append(certs, root)
}
for _, intermediate := range org.MSP().GetTLSIntermediateCerts() {
certs = append(certs, intermediate)
}
orgAddresses[orgName] = orderers.OrdererOrg{
Addresses: org.Endpoints(),
RootCerts: certs,
}
}
}
ordererSource.Update(globalAddresses, orgAddresses)
}
channel := &Channel{
ledger: l,
resources: bundle,
cryptoProvider: p.CryptoProvider,
}
channel.bundleSource = channelconfig.NewBundleSource(
bundle,
ordererSourceCallback,
gossipCallbackWrapper,
trustedRootsCallbackWrapper,
mspCallback,
channel.bundleUpdate,
)
committer := committer.NewLedgerCommitter(l)
validator := &txvalidator.ValidationRouter{
CapabilityProvider: channel,
V14Validator: validatorv14.NewTxValidator(
cid,
p.validationWorkersSemaphore,
channel,
p.pluginMapper,
p.CryptoProvider,
),
V20Validator: validatorv20.NewTxValidator(
cid,
p.validationWorkersSemaphore,
channel,
channel.Ledger(),
&vir.ValidationInfoRetrieveShim{
New: newLifecycleValidation,
Legacy: legacyLifecycleValidation,
},
&CollectionInfoShim{
CollectionAndLifecycleResources: newLifecycleValidation,
ChannelID: bundle.ConfigtxValidator().ChannelID(),
},
p.pluginMapper,
policies.PolicyManagerGetterFunc(p.GetPolicyManager),
p.CryptoProvider,
),
}
// TODO: does someone need to call Close() on the transientStoreFactory at shutdown of the peer?
store, err := p.openStore(bundle.ConfigtxValidator().ChannelID())
if err != nil {
return errors.Wrapf(err, "[channel %s] failed opening transient store", bundle.ConfigtxValidator().ChannelID())
}
channel.store = store
simpleCollectionStore := privdata.NewSimpleCollectionStore(l, deployedCCInfoProvider)
p.GossipService.InitializeChannel(bundle.ConfigtxValidator().ChannelID(), ordererSource, store, gossipservice.Support{
Validator: validator,
Committer: committer,
CollectionStore: simpleCollectionStore,
IdDeserializeFactory: gossipprivdata.IdentityDeserializerFactoryFunc(func(chainID string) msp.IdentityDeserializer {
return mspmgmt.GetManagerForChain(chainID)
}),
CapabilityProvider: channel,
})
p.mutex.Lock()
defer p.mutex.Unlock()
if p.channels == nil {
p.channels = map[string]*Channel{}
}
p.channels[cid] = channel
return nil
}
func (p *Peer) Channel(cid string) *Channel {
p.mutex.RLock()
defer p.mutex.RUnlock()
if c, ok := p.channels[cid]; ok {
return c
}
return nil
}
func (p *Peer) StoreForChannel(cid string) *transientstore.Store {
if c := p.Channel(cid); c != nil {
return c.Store()
}
return nil
}
// GetChannelsInfo returns an array with information about all channels for
// this peer.
func (p *Peer) GetChannelsInfo() []*pb.ChannelInfo {
p.mutex.RLock()
defer p.mutex.RUnlock()
var channelInfos []*pb.ChannelInfo
for key := range p.channels {
ci := &pb.ChannelInfo{ChannelId: key}
channelInfos = append(channelInfos, ci)
}
return channelInfos
}
// GetChannelConfig returns the channel configuration of the channel with channel ID. Note that this
// call returns nil if channel cid has not been created.
func (p *Peer) GetChannelConfig(cid string) channelconfig.Resources {
if c := p.Channel(cid); c != nil {
return c.Resources()
}
return nil
}
// GetStableChannelConfig returns the stable channel configuration of the channel with channel ID.
// Note that this call returns nil if channel cid has not been created.
func (p *Peer) GetStableChannelConfig(cid string) channelconfig.Resources {
if c := p.Channel(cid); c != nil {
return c.Resources()
}
return nil
}
// GetLedger returns the ledger of the channel with channel ID. Note that this
// call returns nil if channel cid has not been created.
func (p *Peer) GetLedger(cid string) ledger.PeerLedger {
if c := p.Channel(cid); c != nil {
return c.Ledger()
}
return nil
}
// GetMSPIDs returns the ID of each application MSP defined on this channel
func (p *Peer) GetMSPIDs(cid string) []string {
if c := p.Channel(cid); c != nil {
return c.GetMSPIDs()
}
return nil
}
// GetPolicyManager returns the policy manager of the channel with channel ID. Note that this
// call returns nil if channel cid has not been created.
func (p *Peer) GetPolicyManager(cid string) policies.Manager {
if c := p.Channel(cid); c != nil {
return c.Resources().PolicyManager()
}
return nil
}
// initChannel takes care to initialize channel after peer joined, for example deploys system CCs
func (p *Peer) initChannel(cid string) {
if p.channelInitializer != nil {
// Initialize chaincode, namely deploy system CC
peerLogger.Debugf("Initializing channel %s", cid)
p.channelInitializer(cid)
}
}
func (p *Peer) GetApplicationConfig(cid string) (channelconfig.Application, bool) {
cc := p.GetChannelConfig(cid)
if cc == nil {
return nil, false
}
return cc.ApplicationConfig()
}
// Initialize sets up any channels that the peer has from the persistence. This
// function should be called at the start up when the ledger and gossip
// ready
func (p *Peer) Initialize(
init func(string),
server *comm.GRPCServer,
pm plugin.Mapper,
deployedCCInfoProvider ledger.DeployedChaincodeInfoProvider,
legacyLifecycleValidation plugindispatcher.LifecycleResources,
newLifecycleValidation plugindispatcher.CollectionAndLifecycleResources,
nWorkers int,
) {
// TODO: exported dep fields or constructor
p.server = server
p.validationWorkersSemaphore = semaphore.New(nWorkers)
p.pluginMapper = pm
p.channelInitializer = init
ledgerIds, err := p.LedgerMgr.GetLedgerIDs()
if err != nil {
panic(fmt.Errorf("error in initializing ledgermgmt: %s", err))
}
for _, cid := range ledgerIds {
peerLogger.Infof("Loading chain %s", cid)
ledger, err := p.LedgerMgr.OpenLedger(cid)
if err != nil {
peerLogger.Errorf("Failed to load ledger %s(%+v)", cid, err)
peerLogger.Debugf("Error while loading ledger %s with message %s. We continue to the next ledger rather than abort.", cid, err)
continue
}
// Create a chain if we get a valid ledger with config block
err = p.createChannel(cid, ledger, deployedCCInfoProvider, legacyLifecycleValidation, newLifecycleValidation)
if err != nil {
peerLogger.Errorf("Failed to load chain %s(%s)", cid, err)
peerLogger.Debugf("Error reloading chain %s with message %s. We continue to the next chain rather than abort.", cid, err)
continue
}
p.initChannel(cid)
}
}