github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/core/ledger/kvledger/tests/util.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package tests
     8  
     9  import (
    10  	"github.com/golang/protobuf/proto"
    11  	"github.com/hyperledger/fabric-protos-go/common"
    12  	"github.com/hyperledger/fabric-protos-go/ledger/rwset"
    13  	"github.com/hyperledger/fabric-protos-go/msp"
    14  	protopeer "github.com/hyperledger/fabric-protos-go/peer"
    15  	configtxtest "github.com/osdi23p228/fabric/common/configtx/test"
    16  	"github.com/osdi23p228/fabric/common/crypto"
    17  	"github.com/osdi23p228/fabric/common/flogging"
    18  	"github.com/osdi23p228/fabric/common/policydsl"
    19  	"github.com/osdi23p228/fabric/core/ledger/kvledger/tests/fakes"
    20  	"github.com/osdi23p228/fabric/internal/pkg/txflags"
    21  	"github.com/osdi23p228/fabric/protoutil"
    22  )
    23  
    24  var logger = flogging.MustGetLogger("test2")
    25  
    26  // collConf helps writing tests with less verbose code by specifying coll configuration
    27  // in a simple struct in place of 'peer.CollectionConfigPackage'. (the test heplers' apis
    28  // use 'collConf' as parameters and return values and transform back and forth to/from proto
    29  // message internally (using func 'convertToCollConfigProtoBytes' and 'convertFromCollConfigProto')
    30  type collConf struct {
    31  	name    string
    32  	btl     uint64
    33  	members []string
    34  }
    35  
    36  type txAndPvtdata struct {
    37  	Txid     string
    38  	Envelope *common.Envelope
    39  	Pvtws    *rwset.TxPvtReadWriteSet
    40  }
    41  
    42  //go:generate counterfeiter -o fakes/signer.go --fake-name Signer . signer
    43  
    44  type signer interface {
    45  	Sign(msg []byte) ([]byte, error)
    46  	Serialize() ([]byte, error)
    47  }
    48  
    49  func convertToCollConfigProtoBytes(collConfs []*collConf) ([]byte, error) {
    50  	var protoConfArray []*protopeer.CollectionConfig
    51  	for _, c := range collConfs {
    52  		protoConf := &protopeer.CollectionConfig{
    53  			Payload: &protopeer.CollectionConfig_StaticCollectionConfig{
    54  				StaticCollectionConfig: &protopeer.StaticCollectionConfig{
    55  					Name:             c.name,
    56  					BlockToLive:      c.btl,
    57  					MemberOrgsPolicy: convertToMemberOrgsPolicy(c.members),
    58  				},
    59  			},
    60  		}
    61  		protoConfArray = append(protoConfArray, protoConf)
    62  	}
    63  	return proto.Marshal(&protopeer.CollectionConfigPackage{Config: protoConfArray})
    64  }
    65  
    66  func convertToMemberOrgsPolicy(members []string) *protopeer.CollectionPolicyConfig {
    67  	var data [][]byte
    68  	for _, member := range members {
    69  		data = append(data, []byte(member))
    70  	}
    71  	return &protopeer.CollectionPolicyConfig{
    72  		Payload: &protopeer.CollectionPolicyConfig_SignaturePolicy{
    73  			SignaturePolicy: policydsl.Envelope(policydsl.Or(policydsl.SignedBy(0), policydsl.SignedBy(1)), data),
    74  		},
    75  	}
    76  }
    77  
    78  func convertFromMemberOrgsPolicy(policy *protopeer.CollectionPolicyConfig) []string {
    79  	if policy.GetSignaturePolicy() == nil {
    80  		return nil
    81  	}
    82  	ids := policy.GetSignaturePolicy().Identities
    83  	var members []string
    84  	for _, id := range ids {
    85  		role := &msp.MSPRole{}
    86  		err := proto.Unmarshal(id.Principal, role)
    87  		if err == nil {
    88  			// This is for sample ledger generated by fabric (e.g., integration test),
    89  			// where id.Principal was properly marshalled during sample ledger generation.
    90  			members = append(members, role.MspIdentifier)
    91  		} else {
    92  			// This is for sample ledger generated by sampleDataHelper.populateLedger,
    93  			// where id.Principal was a []byte cast from a string (not a marshalled msp.MSPRole)
    94  			members = append(members, string(id.Principal))
    95  		}
    96  	}
    97  	return members
    98  }
    99  
   100  func convertFromCollConfigProto(collConfPkg *protopeer.CollectionConfigPackage) []*collConf {
   101  	var collConfs []*collConf
   102  	protoConfArray := collConfPkg.Config
   103  	for _, protoConf := range protoConfArray {
   104  		p := protoConf.GetStaticCollectionConfig()
   105  		collConfs = append(collConfs,
   106  			&collConf{
   107  				name:    p.Name,
   108  				btl:     p.BlockToLive,
   109  				members: convertFromMemberOrgsPolicy(p.MemberOrgsPolicy),
   110  			},
   111  		)
   112  	}
   113  	return collConfs
   114  }
   115  
   116  func constructTransaction(txid string, simulationResults []byte) (*common.Envelope, error) {
   117  	channelid := "dummyChannel"
   118  	ccid := &protopeer.ChaincodeID{
   119  		Name:    "dummyCC",
   120  		Version: "dummyVer",
   121  	}
   122  	txenv, _, err := constructUnsignedTxEnv(
   123  		channelid,
   124  		ccid,
   125  		&protopeer.Response{Status: 200},
   126  		simulationResults,
   127  		txid,
   128  		nil,
   129  		nil,
   130  		common.HeaderType_ENDORSER_TRANSACTION,
   131  	)
   132  	return txenv, err
   133  }
   134  
   135  // constructUnsignedTxEnv creates a Transaction envelope from given inputs
   136  func constructUnsignedTxEnv(
   137  	channelID string,
   138  	ccid *protopeer.ChaincodeID,
   139  	response *protopeer.Response,
   140  	simulationResults []byte,
   141  	txid string,
   142  	events []byte,
   143  	visibility []byte,
   144  	headerType common.HeaderType,
   145  ) (*common.Envelope, string, error) {
   146  
   147  	sigID := &fakes.Signer{}
   148  	sigID.SerializeReturns([]byte("signer"), nil)
   149  	sigID.SignReturns([]byte("signature"), nil)
   150  
   151  	ss, err := sigID.Serialize()
   152  	if err != nil {
   153  		return nil, "", err
   154  	}
   155  
   156  	var prop *protopeer.Proposal
   157  	if txid == "" {
   158  		// if txid is not set, then we need to generate one while creating the proposal message
   159  		prop, txid, err = protoutil.CreateChaincodeProposal(
   160  			headerType,
   161  			channelID,
   162  			&protopeer.ChaincodeInvocationSpec{
   163  				ChaincodeSpec: &protopeer.ChaincodeSpec{
   164  					ChaincodeId: ccid,
   165  				},
   166  			},
   167  			ss,
   168  		)
   169  	} else {
   170  		// if txid is set, we should not generate a txid instead reuse the given txid
   171  		var nonce []byte
   172  		nonce, err = crypto.GetRandomNonce()
   173  		if err != nil {
   174  			return nil, "", err
   175  		}
   176  		prop, txid, err = protoutil.CreateChaincodeProposalWithTxIDNonceAndTransient(
   177  			txid,
   178  			headerType,
   179  			channelID,
   180  			&protopeer.ChaincodeInvocationSpec{
   181  				ChaincodeSpec: &protopeer.ChaincodeSpec{
   182  					ChaincodeId: ccid,
   183  				},
   184  			},
   185  			nonce,
   186  			ss,
   187  			nil,
   188  		)
   189  		if err != nil {
   190  			return nil, "", err
   191  		}
   192  	}
   193  
   194  	presp, err := protoutil.CreateProposalResponse(
   195  		prop.Header,
   196  		prop.Payload,
   197  		response,
   198  		simulationResults,
   199  		nil,
   200  		ccid,
   201  		sigID,
   202  	)
   203  	if err != nil {
   204  		return nil, "", err
   205  	}
   206  
   207  	env, err := protoutil.CreateSignedTx(prop, sigID, presp)
   208  	if err != nil {
   209  		return nil, "", err
   210  	}
   211  	return env, txid, nil
   212  }
   213  
   214  func constructTestGenesisBlock(channelid string) (*common.Block, error) {
   215  	blk, err := configtxtest.MakeGenesisBlock(channelid)
   216  	if err != nil {
   217  		return nil, err
   218  	}
   219  	setBlockFlagsToValid(blk)
   220  	return blk, nil
   221  }
   222  
   223  func setBlockFlagsToValid(block *common.Block) {
   224  	protoutil.InitBlockMetadata(block)
   225  	block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] =
   226  		txflags.NewWithValues(len(block.Data.Data), protopeer.TxValidationCode_VALID)
   227  }