Ejemplo n.º 1
0
// Invoke a chaincode.
func invoke(ctx context.Context, chainID string, spec *pb.ChaincodeSpec) (ccevt *pb.ChaincodeEvent, uuid string, retval []byte, err error) {
	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	// Now create the Transactions message and send to Peer.
	uuid = util.GenerateUUID()

	var txsim ledger.TxSimulator
	ctx, txsim, err = startTxSimulation(ctx, chainID)
	if err != nil {
		return nil, uuid, nil, fmt.Errorf("Failed to get handle to simulator: %s ", err)
	}

	defer func() {
		//no error, lets try commit
		if err == nil {
			//capture returned error from commit
			err = endTxSimulationCIS(chainID, uuid, txsim, []byte("invoke"), true, chaincodeInvocationSpec)
		} else {
			//there was an error, just close simulation and return that
			endTxSimulationCIS(chainID, uuid, txsim, []byte("invoke"), false, chaincodeInvocationSpec)
		}
	}()

	cccid := NewCCContext(chainID, chaincodeInvocationSpec.ChaincodeSpec.ChaincodeID.Name, "", uuid, false, nil)
	retval, ccevt, err = Execute(ctx, cccid, chaincodeInvocationSpec)
	if err != nil {
		return nil, uuid, nil, fmt.Errorf("Error invoking chaincode: %s ", err)
	}

	return ccevt, uuid, retval, err
}
Ejemplo n.º 2
0
func newLockBasedTxSimulator(txmgr *LockBasedTxMgr) *lockBasedTxSimulator {
	rwset := rwset.NewRWSet()
	helper := &queryHelper{txmgr: txmgr, rwset: rwset}
	id := util.GenerateUUID()
	logger.Debugf("constructing new tx simulator [%s]", id)
	return &lockBasedTxSimulator{lockBasedQueryExecutor{helper, id}, rwset}
}
Ejemplo n.º 3
0
// EXP_ExecuteWithBinding executes a transaction with a specific binding/TXHandler
func (d *Devops) EXP_ExecuteWithBinding(ctx context.Context, executeWithBinding *pb.ExecuteWithBinding) (*pb.Response, error) {

	if d.isSecurityEnabled {
		devopsLogger.Debug("Getting TxHandler for binding")

		txHandler, err := d.bindingMap.getTxHandlerForBinding(executeWithBinding.Binding)

		if nil != err {
			return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte(err.Error())}, nil
		}

		tid := util.GenerateUUID()

		tx, err := txHandler.NewChaincodeExecute(executeWithBinding.ChaincodeInvocationSpec, tid)
		if err != nil {
			return nil, fmt.Errorf("Error creating executing with binding:  %s", err)
		}

		return d.coord.ExecuteTransaction(tx), nil
		//return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte("NOT IMPLEMENTED")}, nil

		//return &pb.Response{Status: pb.Response_SUCCESS, Msg: sigmaOutputBytes}, nil
	}
	devopsLogger.Warning("Security NOT enabled")
	return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte("Security NOT enabled")}, nil
}
Ejemplo n.º 4
0
// Invoke or query a chaincode.
func invoke(ctx context.Context, spec *pb.ChaincodeSpec, typ pb.Transaction_Type) (*pb.ChaincodeEvent, string, []byte, error) {
	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	// Now create the Transactions message and send to Peer.
	uuid := util.GenerateUUID()

	var transaction *pb.Transaction
	var err error
	transaction, err = pb.NewChaincodeExecute(chaincodeInvocationSpec, uuid, typ)
	if err != nil {
		return nil, uuid, nil, fmt.Errorf("Error invoking chaincode: %s ", err)
	}

	var retval []byte
	var execErr error
	var ccevt *pb.ChaincodeEvent
	if typ == pb.Transaction_CHAINCODE_QUERY {
		retval, ccevt, execErr = chaincode.Execute(ctx, chaincode.GetChain(chaincode.DefaultChain), transaction)
	} else {
		ledger, _ := ledger.GetLedger()
		ledger.BeginTxBatch("1")
		retval, ccevt, execErr = chaincode.Execute(ctx, chaincode.GetChain(chaincode.DefaultChain), transaction)
		if err != nil {
			return nil, uuid, nil, fmt.Errorf("Error invoking chaincode: %s ", err)
		}
		ledger.CommitTxBatch("1", []*pb.Transaction{transaction}, nil, nil)
	}

	return ccevt, uuid, retval, execErr
}
Ejemplo n.º 5
0
func getProposal() (*peer.Proposal, error) {
	cis := &peer.ChaincodeInvocationSpec{
		ChaincodeSpec: &peer.ChaincodeSpec{
			ChaincodeID: &peer.ChaincodeID{Name: "foo"},
			Type:        peer.ChaincodeSpec_GOLANG}}

	uuid := util.GenerateUUID()

	return utils.CreateProposalFromCIS(uuid, util.GetTestChainID(), cis, signerSerialized)
}
Ejemplo n.º 6
0
func (d *Devops) invokeOrQuery(ctx context.Context, chaincodeInvocationSpec *pb.ChaincodeInvocationSpec, attributes []string, invoke bool) (*pb.Response, error) {

	if chaincodeInvocationSpec.ChaincodeSpec.ChaincodeID.Name == "" {
		return nil, fmt.Errorf("name not given for invoke/query")
	}

	// Now create the Transactions message and send to Peer.
	var customIDgenAlg = strings.ToLower(chaincodeInvocationSpec.IdGenerationAlg)
	var id string
	var generr error
	if customIDgenAlg != "" {
		id, generr = util.GenerateIDWithAlg(customIDgenAlg, chaincodeInvocationSpec.ChaincodeSpec.CtorMsg.Args[0])
		if generr != nil {
			return nil, generr
		}
	} else {
		id = util.GenerateUUID()
	}
	devopsLogger.Infof("Transaction ID: %v", id)
	var transaction *pb.Transaction
	var err error
	var sec crypto.Client
	if peer.SecurityEnabled() {
		if devopsLogger.IsEnabledFor(logging.DEBUG) {
			devopsLogger.Debugf("Initializing secure devops using context %s", chaincodeInvocationSpec.ChaincodeSpec.SecureContext)
		}
		sec, err = crypto.InitClient(chaincodeInvocationSpec.ChaincodeSpec.SecureContext, nil)
		defer crypto.CloseClient(sec)
		// remove the security context since we are no longer need it down stream
		chaincodeInvocationSpec.ChaincodeSpec.SecureContext = ""
		if nil != err {
			return nil, err
		}
	}

	transaction, err = d.createExecTx(chaincodeInvocationSpec, attributes, id, invoke, sec)
	if err != nil {
		return nil, err
	}
	if devopsLogger.IsEnabledFor(logging.DEBUG) {
		devopsLogger.Debugf("Sending invocation transaction (%s) to validator", transaction.Uuid)
	}
	resp := d.coord.ExecuteTransaction(transaction)
	if resp.Status == pb.Response_FAILURE {
		err = fmt.Errorf(string(resp.Msg))
	} else {
		if !invoke && nil != sec && viper.GetBool("security.privacy") {
			if resp.Msg, err = sec.DecryptQueryResult(transaction, resp.Msg); nil != err {
				devopsLogger.Errorf("Failed decrypting query transaction result %s", string(resp.Msg[:]))
				//resp = &pb.Response{Status: pb.Response_FAILURE, Msg: []byte(err.Error())}
			}
		}
	}
	return resp, err
}
Ejemplo n.º 7
0
// ConstructTransaction constructs a transaction for testing
func ConstructTransaction(t *testing.T, simulationResults []byte, sign bool) (*common.Envelope, string, error) {
	ccName := "foo"
	txID := util.GenerateUUID()
	var txEnv *common.Envelope
	var err error
	if sign {
		txEnv, err = ptestutils.ConstructSingedTxEnvWithDefaultSigner(txID, util.GetTestChainID(), ccName, simulationResults, nil, nil)
	} else {
		txEnv, err = ptestutils.ConstructUnsingedTxEnv(txID, util.GetTestChainID(), ccName, simulationResults, nil, nil)
	}
	return txEnv, txID, err
}
Ejemplo n.º 8
0
func transferOwnershipInternal(owner crypto.Client, ownerCert crypto.CertificateHandler, asset string, newOwnerCert crypto.CertificateHandler) (resp *pb.Response, err error) {
	// Get a transaction handler to be used to submit the execute transaction
	// and bind the chaincode access control logic using the binding

	submittingCertHandler, err := owner.GetTCertificateHandlerNext()
	if err != nil {
		return nil, err
	}
	txHandler, err := submittingCertHandler.GetTransactionHandler()
	if err != nil {
		return nil, err
	}
	binding, err := txHandler.GetBinding()
	if err != nil {
		return nil, err
	}

	chaincodeInput := &pb.ChaincodeInput{
		Function: "transfer",
		Args:     []string{asset, base64.StdEncoding.EncodeToString(newOwnerCert.GetCertificate())},
	}
	chaincodeInputRaw, err := proto.Marshal(chaincodeInput)
	if err != nil {
		return nil, err
	}

	// Access control. Owner signs chaincodeInputRaw || binding to confirm his identity
	sigma, err := ownerCert.Sign(append(chaincodeInputRaw, binding...))
	if err != nil {
		return nil, err
	}

	// Prepare spec and submit
	spec := &pb.ChaincodeSpec{
		Type:                 1,
		ChaincodeID:          &pb.ChaincodeID{Name: chaincodeName},
		CtorMsg:              chaincodeInput,
		Metadata:             sigma, // Proof of identity
		ConfidentialityLevel: confidentialityLevel,
	}

	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	// Now create the Transactions message and send to Peer.
	transaction, err := txHandler.NewChaincodeExecute(chaincodeInvocationSpec, util.GenerateUUID())
	if err != nil {
		return nil, fmt.Errorf("Error deploying chaincode: %s ", err)
	}

	return processTransaction(transaction)

}
Ejemplo n.º 9
0
func (b *BDDContext) weCompose(composeFiles string) error {
	if b.composition != nil {
		return fmt.Errorf("Already have composition in BDD context (%s)", b.composition.projectName)
	}
	// Need a unique name, but docker does not allow '-' in names
	composeProjectName := strings.Replace(util.GenerateUUID(), "-", "", -1)
	newComposition, err := NewComposition(composeProjectName, composeFiles)
	if err != nil {
		return fmt.Errorf("Error composing system in BDD context:  %s", err)
	}
	b.composition = newComposition
	return nil
}
Ejemplo n.º 10
0
func (node *nodeImpl) getTLSCertificateFromTLSCA(id, affiliation string) (interface{}, []byte, error) {
	node.Debug("getTLSCertificate...")

	priv, err := primitives.NewECDSAKey()

	if err != nil {
		node.Errorf("Failed generating key: %s", err)

		return nil, nil, err
	}

	uuid := util.GenerateUUID()

	// Prepare the request
	pubraw, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
	now := time.Now()
	timestamp := timestamp.Timestamp{Seconds: int64(now.Second()), Nanos: int32(now.Nanosecond())}

	req := &membersrvc.TLSCertCreateReq{
		Ts: &timestamp,
		Id: &membersrvc.Identity{Id: id + "-" + uuid},
		Pub: &membersrvc.PublicKey{
			Type: membersrvc.CryptoType_ECDSA,
			Key:  pubraw,
		}, Sig: nil}
	rawreq, _ := proto.Marshal(req)
	r, s, err := ecdsa.Sign(rand.Reader, priv, primitives.Hash(rawreq))
	if err != nil {
		panic(err)
	}
	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &membersrvc.Signature{Type: membersrvc.CryptoType_ECDSA, R: R, S: S}

	pbCert, err := node.callTLSCACreateCertificate(context.Background(), req)
	if err != nil {
		node.Errorf("Failed requesting tls certificate: %s", err)

		return nil, nil, err
	}

	node.Debug("Verifing tls certificate...")

	tlsCert, err := primitives.DERToX509Certificate(pbCert.Cert.Cert)
	certPK := tlsCert.PublicKey.(*ecdsa.PublicKey)
	primitives.VerifySignCapability(priv, certPK)

	node.Debug("Verifing tls certificate...done!")

	return priv, pbCert.Cert.Cert, nil
}
Ejemplo n.º 11
0
// deploySysCC deploys the given system chaincode on a chain
func deploySysCC(chainID string, syscc *SystemChaincode) error {
	if !syscc.Enabled || !isWhitelisted(syscc) {
		sysccLogger.Info(fmt.Sprintf("system chaincode (%s,%s) disabled", syscc.Name, syscc.Path))
		return nil
	}

	if chainID == "" && !syscc.ChainlessCC {
		return fmt.Errorf("cannot deploy system chaincode %s without chain id", syscc.Name)
	} else if chainID != "" && syscc.ChainlessCC {
		return fmt.Errorf("cannot deploy chainless system chaincode %s with chain id %s", syscc.Name, chainID)
	}

	var err error

	ctxt := context.Background()
	if !syscc.ChainlessCC {
		lgr := peer.GetLedger(chainID)
		var txsim ledger.TxSimulator
		if txsim, err = lgr.NewTxSimulator(); err != nil {
			return err
		}

		ctxt = context.WithValue(ctxt, TXSimulatorKey, txsim)

		defer txsim.Done()
	}

	chaincodeID := &pb.ChaincodeID{Path: syscc.Path, Name: syscc.Name}
	spec := &pb.ChaincodeSpec{Type: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value["GOLANG"]), ChaincodeID: chaincodeID, CtorMsg: &pb.ChaincodeInput{Args: syscc.InitArgs}}

	// First build and get the deployment spec
	chaincodeDeploymentSpec, err := buildSysCC(ctxt, spec)

	if err != nil {
		sysccLogger.Error(fmt.Sprintf("Error deploying chaincode spec: %v\n\n error: %s", spec, err))
		return err
	}

	txid := util.GenerateUUID()

	cccid := NewCCContext(chainID, chaincodeDeploymentSpec.ChaincodeSpec.ChaincodeID.Name, "", txid, true, nil)

	_, _, err = Execute(ctxt, cccid, chaincodeDeploymentSpec)

	sysccLogger.Infof("system chaincode %s/%s(%s) deployed", syscc.Name, chainID, syscc.Path)

	return err
}
Ejemplo n.º 12
0
func createConfidentialECertHDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
	uuid := util.GenerateUUID()

	cds := &obc.ChaincodeDeploymentSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
		},
		EffectiveDate: nil,
		CodePackage:   nil,
	}

	otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
	if err != nil {
		return nil, nil, err
	}
	handler, err := deployer.GetEnrollmentCertificateHandler()
	if err != nil {
		return nil, nil, err
	}
	txHandler, err := handler.GetTransactionHandler()
	if err != nil {
		return nil, nil, err
	}
	tx, err := txHandler.NewChaincodeDeployTransaction(cds, uuid)

	// Check binding consistency
	binding, _ := txHandler.GetBinding()
	if !reflect.DeepEqual(binding, primitives.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
		t.Fatal("Binding is malformed!")
	}

	// Check confidentiality level
	if tx.ConfidentialityLevel != cds.ChaincodeSpec.ConfidentialityLevel {
		t.Fatal("Failed setting confidentiality level")
	}

	// Check metadata
	if !reflect.DeepEqual(cds.ChaincodeSpec.Metadata, tx.Metadata) {
		t.Fatal("Failed copying metadata")
	}

	return otx, tx, err
}
Ejemplo n.º 13
0
func TestParallelInitClose(t *testing.T) {
	// TODO: complete this
	conf := utils.NodeConfiguration{Type: "client", Name: "userthread"}
	RegisterClient(conf.Name, nil, conf.GetEnrollmentID(), conf.GetEnrollmentPWD())

	done := make(chan bool)

	n := 10
	for i := 0; i < n; i++ {
		go func() {
			for i := 0; i < 5; i++ {
				client, err := InitClient(conf.Name, nil)
				if err != nil {
					t.Log("Init failed")
				}

				cis := &obc.ChaincodeInvocationSpec{
					ChaincodeSpec: &obc.ChaincodeSpec{
						Type:                 obc.ChaincodeSpec_GOLANG,
						ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
						CtorMsg:              nil,
						ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
					},
				}
				for i := 0; i < 20; i++ {
					uuid := util.GenerateUUID()
					client.NewChaincodeExecute(cis, uuid)
				}

				err = CloseClient(client)
				if err != nil {
					t.Log("Close failed")
				}
			}
			done <- true

		}()
	}
	for i := 0; i < n; i++ {
		log.Info("Waiting")
		<-done
		log.Info("+1")
	}
	log.Info("Test Finished!")
	//
}
Ejemplo n.º 14
0
//deploy the command via Endorser
func deploy(cmd *cobra.Command, cf *ChaincodeCmdFactory) (*protcommon.Envelope, error) {
	spec, err := getChaincodeSpecification(cmd)
	if err != nil {
		return nil, err
	}

	cds, err := getChaincodeBytes(spec)
	if err != nil {
		return nil, fmt.Errorf("Error getting chaincode code %s: %s", chainFuncName, err)
	}

	creator, err := cf.Signer.Serialize()
	if err != nil {
		return nil, fmt.Errorf("Error serializing identity for %s: %s\n", cf.Signer.GetIdentifier(), err)
	}

	uuid := util.GenerateUUID()

	prop, err := utils.CreateDeployProposalFromCDS(uuid, chainID, cds, creator)
	if err != nil {
		return nil, fmt.Errorf("Error creating proposal  %s: %s\n", chainFuncName, err)
	}

	var signedProp *pb.SignedProposal
	signedProp, err = utils.GetSignedProposal(prop, cf.Signer)
	if err != nil {
		return nil, fmt.Errorf("Error creating signed proposal  %s: %s\n", chainFuncName, err)
	}

	proposalResponse, err := cf.EndorserClient.ProcessProposal(context.Background(), signedProp)
	if err != nil {
		return nil, fmt.Errorf("Error endorsing %s: %s\n", chainFuncName, err)
	}

	if proposalResponse != nil {
		// assemble a signed transaction (it's an Envelope message)
		env, err := utils.CreateSignedTx(prop, cf.Signer, proposalResponse)
		if err != nil {
			return nil, fmt.Errorf("Could not assemble transaction, err %s", err)
		}

		return env, nil
	}

	return nil, nil
}
func createTx() (*common.Envelope, error) {
	cis := &peer.ChaincodeInvocationSpec{ChaincodeSpec: &peer.ChaincodeSpec{ChaincodeID: &peer.ChaincodeID{Name: "foo"}}}

	uuid := util.GenerateUUID()

	prop, err := utils.CreateProposalFromCIS(uuid, util.GetTestChainID(), cis, sid)
	if err != nil {
		return nil, err
	}

	presp, err := utils.CreateProposalResponse(prop.Header, prop.Payload, []byte("res"), nil, nil, id)
	if err != nil {
		return nil, err
	}

	return utils.CreateSignedTx(prop, id, presp)
}
Ejemplo n.º 16
0
func createConfidentialTCertHQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
	uuid := util.GenerateUUID()

	cis := &obc.ChaincodeInvocationSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
		},
	}

	otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
	if err != nil {
		return nil, nil, err
	}
	handler, err := invoker.GetTCertificateHandlerNext()
	if err != nil {
		return nil, nil, err
	}
	txHandler, err := handler.GetTransactionHandler()
	if err != nil {
		return nil, nil, err
	}
	tx, err := txHandler.NewChaincodeQuery(cis, uuid)

	// Check binding consistency
	binding, _ := txHandler.GetBinding()
	if !reflect.DeepEqual(binding, primitives.Hash(append(handler.GetCertificate(), tx.Nonce...))) {
		t.Fatal("Binding is malformed!")
	}

	// Check confidentiality level
	if tx.ConfidentialityLevel != cis.ChaincodeSpec.ConfidentialityLevel {
		t.Fatal("Failed setting confidentiality level")
	}

	// Check metadata
	if !reflect.DeepEqual(cis.ChaincodeSpec.Metadata, tx.Metadata) {
		t.Fatal("Failed copying metadata")
	}

	return otx, tx, err
}
Ejemplo n.º 17
0
func createPublicQueryTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
	uuid := util.GenerateUUID()

	cis := &obc.ChaincodeInvocationSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_PUBLIC,
		},
	}

	otx, err := obc.NewChaincodeExecute(cis, uuid, obc.Transaction_CHAINCODE_QUERY)
	if err != nil {
		return nil, nil, err
	}
	tx, err := invoker.NewChaincodeQuery(cis, uuid)
	return otx, tx, err
}
Ejemplo n.º 18
0
func executeJoin(cf *JoinCmdFactory) (err error) {
	spec, err := getJoinCCSpec()
	if err != nil {
		return err
	}

	// Build the ChaincodeInvocationSpec message
	invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	creator, err := cf.Signer.Serialize()
	if err != nil {
		return fmt.Errorf("Error serializing identity for %s: %s\n", cf.Signer.GetIdentifier(), err)
	}

	uuid := cutil.GenerateUUID()

	var prop *pb.Proposal
	prop, err = putils.CreateProposalFromCIS(uuid, "", invocation, creator)
	if err != nil {
		return fmt.Errorf("Error creating proposal for join %s\n", err)
	}

	var signedProp *pb.SignedProposal
	signedProp, err = putils.GetSignedProposal(prop, cf.Signer)
	if err != nil {
		return fmt.Errorf("Error creating signed proposal  %s\n", err)
	}

	var proposalResp *pb.ProposalResponse
	proposalResp, err = cf.EndorserClient.ProcessProposal(context.Background(), signedProp)
	if err != nil {
		return fmt.Errorf("Error endorsing %s\n", err)
	}

	if proposalResp == nil {
		return fmt.Errorf("Error on join by endorsing: %s\n", err)
	}

	fmt.Printf("Join Result: %s\n", string(proposalResp.Response.Payload))

	return nil
}
Ejemplo n.º 19
0
func BenchmarkTransactionCreation(b *testing.B) {
	b.StopTimer()
	b.ResetTimer()
	cis := &obc.ChaincodeInvocationSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_CONFIDENTIAL,
		},
	}
	invoker.GetTCertificateHandlerNext()

	for i := 0; i < b.N; i++ {
		uuid := util.GenerateUUID()
		b.StartTimer()
		invoker.NewChaincodeExecute(cis, uuid)
		b.StopTimer()
	}
}
Ejemplo n.º 20
0
func createPublicDeployTransaction(t *testing.T) (*obc.Transaction, *obc.Transaction, error) {
	uuid := util.GenerateUUID()

	cds := &obc.ChaincodeDeploymentSpec{
		ChaincodeSpec: &obc.ChaincodeSpec{
			Type:                 obc.ChaincodeSpec_GOLANG,
			ChaincodeID:          &obc.ChaincodeID{Path: "Contract001"},
			CtorMsg:              nil,
			ConfidentialityLevel: obc.ConfidentialityLevel_PUBLIC,
		},
		EffectiveDate: nil,
		CodePackage:   nil,
	}

	otx, err := obc.NewChaincodeDeployTransaction(cds, uuid)
	if err != nil {
		return nil, nil, err
	}
	tx, err := deployer.NewChaincodeDeployTransaction(cds, uuid)
	return otx, tx, err
}
Ejemplo n.º 21
0
func deploy2(ctx context.Context, cccid *CCContext, chaincodeDeploymentSpec *pb.ChaincodeDeploymentSpec) (b []byte, err error) {
	cis, err := getDeployLCCCSpec(cccid.ChainID, chaincodeDeploymentSpec)
	if err != nil {
		return nil, fmt.Errorf("Error creating lccc spec : %s\n", err)
	}

	ctx, txsim, err := startTxSimulation(ctx, cccid.ChainID)
	if err != nil {
		return nil, fmt.Errorf("Failed to get handle to simulator: %s ", err)
	}

	uuid := util.GenerateUUID()

	cccid.TxID = uuid

	defer func() {
		//no error, lets try commit
		if err == nil {
			//capture returned error from commit
			err = endTxSimulationCDS(cccid.ChainID, uuid, txsim, []byte("deployed"), true, chaincodeDeploymentSpec)
		} else {
			//there was an error, just close simulation and return that
			endTxSimulationCDS(cccid.ChainID, uuid, txsim, []byte("deployed"), false, chaincodeDeploymentSpec)
		}
	}()

	lcccid := NewCCContext(cccid.ChainID, cis.ChaincodeSpec.ChaincodeID.Name, "", uuid, true, nil)

	//write to lccc
	if _, _, err = Execute(ctx, lcccid, cis); err != nil {
		return nil, fmt.Errorf("Error deploying chaincode: %s", err)
	}

	if b, _, err = Execute(ctx, cccid, chaincodeDeploymentSpec); err != nil {
		return nil, fmt.Errorf("Error deploying chaincode: %s", err)
	}

	return b, nil
}
Ejemplo n.º 22
0
func whoIsTheOwner(invoker crypto.Client, asset string) (transaction *pb.Transaction, resp *pb.Response, err error) {
	chaincodeInput := &pb.ChaincodeInput{Args: util.ToChaincodeArgs("query", asset)}

	// Prepare spec and submit
	spec := &pb.ChaincodeSpec{
		Type:                 1,
		ChaincodeID:          &pb.ChaincodeID{Name: chaincodeName},
		CtorMsg:              chaincodeInput,
		ConfidentialityLevel: confidentialityLevel,
	}

	chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}

	// Now create the Transactions message and send to Peer.
	transaction, err = invoker.NewChaincodeQuery(chaincodeInvocationSpec, util.GenerateUUID())
	if err != nil {
		return nil, nil, fmt.Errorf("Error deploying chaincode: %s ", err)
	}

	resp, err = processTransaction(transaction)
	return
}
Ejemplo n.º 23
0
func requestTLSCertificate(t *testing.T) {
	var opts []grpc.DialOption

	creds, err := credentials.NewClientTLSFromFile(viper.GetString("server.tls.cert.file"), "tlsca")
	if err != nil {
		t.Logf("Failed creating credentials for TLS-CA client: %s", err)
		t.Fail()
	}

	opts = append(opts, grpc.WithTransportCredentials(creds))
	sockP, err := grpc.Dial(viper.GetString("peer.pki.tlsca.paddr"), opts...)
	if err != nil {
		t.Logf("Failed dialing in: %s", err)
		t.Fail()
	}

	defer sockP.Close()

	tlscaP := membersrvc.NewTLSCAPClient(sockP)

	// Prepare the request
	id := "peer"
	priv, err := primitives.NewECDSAKey()

	if err != nil {
		t.Logf("Failed generating key: %s", err)
		t.Fail()
	}

	uuid := util.GenerateUUID()

	pubraw, _ := x509.MarshalPKIXPublicKey(&priv.PublicKey)
	now := time.Now()
	timestamp := timestamp.Timestamp{Seconds: int64(now.Second()), Nanos: int32(now.Nanosecond())}

	req := &membersrvc.TLSCertCreateReq{
		Ts: &timestamp,
		Id: &membersrvc.Identity{Id: id + "-" + uuid},
		Pub: &membersrvc.PublicKey{
			Type: membersrvc.CryptoType_ECDSA,
			Key:  pubraw,
		}, Sig: nil}

	rawreq, _ := proto.Marshal(req)
	r, s, err := ecdsa.Sign(rand.Reader, priv, primitives.Hash(rawreq))

	if err != nil {
		t.Logf("Failed signing the request: %s", err)
		t.Fail()
	}

	R, _ := r.MarshalText()
	S, _ := s.MarshalText()
	req.Sig = &membersrvc.Signature{Type: membersrvc.CryptoType_ECDSA, R: R, S: S}

	resp, err := tlscaP.CreateCertificate(context.Background(), req)
	if err != nil {
		t.Logf("Failed requesting tls certificate: %s", err)
		t.Fail()
	}

	storePrivateKeyInClear("tls_peer.priv", priv, t)
	storeCert("tls_peer.cert", resp.Cert.Cert, t)
	storeCert("tls_peer.ca", resp.RootCert.Cert, t)
}
Ejemplo n.º 24
0
func buildTestTx(tb testing.TB) (*protos.Transaction, string) {
	uuid := util.GenerateUUID()
	tx, err := protos.NewTransaction(protos.ChaincodeID{Path: "testUrl"}, uuid, "anyfunction", []string{"param1, param2"})
	testutil.AssertNil(tb, err)
	return tx, uuid
}
Ejemplo n.º 25
0
//getProposal gets the proposal for the chaincode invocation
//Currently supported only for Invokes (Queries still go through devops client)
func getInvokeProposal(cis *pb.ChaincodeInvocationSpec, chainID string, creator []byte) (*pb.Proposal, error) {
	uuid := util.GenerateUUID()
	return pbutils.CreateChaincodeProposal(uuid, chainID, cis, creator)
}
Ejemplo n.º 26
0
func constructTransaction(simulationResults []byte) *common.Envelope {
	txEnv, _ := ptestutils.ConstructSingedTxEnvWithDefaultSigner(util.GenerateUUID(), util.GetTestChainID(), "foo", simulationResults, nil, nil)
	return txEnv
}
Ejemplo n.º 27
0
func generateUUID(t *testing.T) string {
	return util.GenerateUUID()
}
Ejemplo n.º 28
0
			Expect(ledgerPtr.RollbackTxBatch(1)).To(BeNil())
			state, _ := ledgerPtr.GetState("chaincode1", "key1", false)
			Expect(state).To(BeNil())
			state, _ = ledgerPtr.GetState("chaincode2", "key2", false)
			Expect(state).To(BeNil())
			state, _ = ledgerPtr.GetState("chaincode3", "key3", false)
			Expect(state).To(BeNil())
			state, _ = ledgerPtr.GetState("chaincode1", "key1", true)
			Expect(state).To(BeNil())
			state, _ = ledgerPtr.GetState("chaincode2", "key2", true)
			Expect(state).To(BeNil())
			state, _ = ledgerPtr.GetState("chaincode3", "key3", true)
			Expect(state).To(BeNil())
		})
		It("should commit the batch with the correct ID", func() {
			uuid := util.GenerateUUID()
			tx, err := protos.NewTransaction(protos.ChaincodeID{Path: "testUrl"}, uuid, "anyfunction", []string{"param1, param2"})
			Expect(err).To(BeNil())
			err = ledgerPtr.CommitTxBatch(1, []*protos.Transaction{tx}, nil, []byte("proof"))
			Expect(err).To(BeNil())
			state, _ := ledgerPtr.GetState("chaincode1", "key1", false)
			Expect(state).To(Equal([]byte("value1")))
			state, _ = ledgerPtr.GetState("chaincode2", "key2", false)
			Expect(state).To(Equal([]byte("value2")))
			state, _ = ledgerPtr.GetState("chaincode3", "key3", false)
			Expect(state).To(Equal([]byte("value3")))
			state, _ = ledgerPtr.GetState("chaincode1", "key1", true)
			Expect(state).To(Equal([]byte("value1")))
			state, _ = ledgerPtr.GetState("chaincode2", "key2", true)
			Expect(state).To(Equal([]byte("value2")))
			state, _ = ledgerPtr.GetState("chaincode3", "key3", true)
Ejemplo n.º 29
0
func constructDummyTx(tb testing.TB) *protos.Transaction {
	uuid := util.GenerateUUID()
	tx, err := protos.NewTransaction(protos.ChaincodeID{Path: "dummyChaincodeId"}, uuid, "dummyFunction", []string{"dummyParamValue1, dummyParamValue2"})
	testutil.AssertNil(tb, err)
	return tx
}
Ejemplo n.º 30
0
// chaincodeInvokeOrQuery invokes or queries the chaincode. If successful, the
// INVOKE form prints the ProposalResponse to STDOUT, and the QUERY form prints
// the query result on STDOUT. A command-line flag (-r, --raw) determines
// whether the query result is output as raw bytes, or as a printable string.
// The printable form is optionally (-x, --hex) a hexadecimal representation
// of the query response. If the query response is NIL, nothing is output.
//
// NOTE - Query will likely go away as all interactions with the endorser are
// Proposal and ProposalResponses
func chaincodeInvokeOrQuery(cmd *cobra.Command, args []string, invoke bool, cf *ChaincodeCmdFactory) (err error) {
	spec, err := getChaincodeSpecification(cmd)
	if err != nil {
		return err
	}

	// Build the ChaincodeInvocationSpec message
	invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}
	if customIDGenAlg != common.UndefinedParamValue {
		invocation.IdGenerationAlg = customIDGenAlg
	}

	creator, err := cf.Signer.Serialize()
	if err != nil {
		return fmt.Errorf("Error serializing identity for %s: %s\n", cf.Signer.GetIdentifier(), err)
	}

	uuid := cutil.GenerateUUID()

	var prop *pb.Proposal
	prop, err = putils.CreateProposalFromCIS(uuid, chainID, invocation, creator)
	if err != nil {
		return fmt.Errorf("Error creating proposal  %s: %s\n", chainFuncName, err)
	}

	var signedProp *pb.SignedProposal
	signedProp, err = putils.GetSignedProposal(prop, cf.Signer)
	if err != nil {
		return fmt.Errorf("Error creating signed proposal  %s: %s\n", chainFuncName, err)
	}

	var proposalResp *pb.ProposalResponse
	proposalResp, err = cf.EndorserClient.ProcessProposal(context.Background(), signedProp)
	if err != nil {
		return fmt.Errorf("Error endorsing %s: %s\n", chainFuncName, err)
	}

	if invoke {
		if proposalResp != nil {
			// assemble a signed transaction (it's an Envelope message)
			env, err := putils.CreateSignedTx(prop, cf.Signer, proposalResp)
			if err != nil {
				return fmt.Errorf("Could not assemble transaction, err %s", err)
			}

			// send the envelope for ordering
			if err = cf.BroadcastClient.Send(env); err != nil {
				return fmt.Errorf("Error sending transaction %s: %s\n", chainFuncName, err)
			}
		}
		logger.Infof("Invoke result: %v", proposalResp)
	} else {
		if proposalResp == nil {
			return fmt.Errorf("Error query %s by endorsing: %s\n", chainFuncName, err)
		}

		if chaincodeQueryRaw {
			if chaincodeQueryHex {
				err = errors.New("Options --raw (-r) and --hex (-x) are not compatible\n")
				return
			}
			fmt.Print("Query Result (Raw): ")
			os.Stdout.Write(proposalResp.Response.Payload)
		} else {
			if chaincodeQueryHex {
				fmt.Printf("Query Result: %x\n", proposalResp.Response.Payload)
			} else {
				fmt.Printf("Query Result: %s\n", string(proposalResp.Response.Payload))
			}
		}
	}

	return nil
}