當前位置: 首頁>>代碼示例>>Golang>>正文


Golang ChaincodeStubInterface.GetState方法代碼示例

本文整理匯總了Golang中github.com/hyperledger/fabric/core/chaincode/shim.ChaincodeStubInterface.GetState方法的典型用法代碼示例。如果您正苦於以下問題:Golang ChaincodeStubInterface.GetState方法的具體用法?Golang ChaincodeStubInterface.GetState怎麽用?Golang ChaincodeStubInterface.GetState使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/hyperledger/fabric/core/chaincode/shim.ChaincodeStubInterface的用法示例。


在下文中一共展示了ChaincodeStubInterface.GetState方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Query

// Query callback representing the query of a chaincode
func (t *SampleSysCC) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function != "getval" {
		return nil, errors.New("Invalid query function name. Expecting \"getval\"")
	}
	var key string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting key to query")
	}

	key = args[0]

	// Get the state from the ledger
	valbytes, err := stub.GetState(key)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + key + "\"}"
		return nil, errors.New(jsonResp)
	}

	if valbytes == nil {
		jsonResp := "{\"Error\":\"Nil val for " + key + "\"}"
		return nil, errors.New(jsonResp)
	}

	return valbytes, nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:28,代碼來源:samplesyscc.go

示例2: findMarble4Trade

// ============================================================================================================================
// findMarble4Trade - look for a matching marble that this user owns and return it
// ============================================================================================================================
func findMarble4Trade(stub shim.ChaincodeStubInterface, user string, color string, size int) (m Marble, err error) {
	var fail Marble
	fmt.Println("- start find marble 4 trade")
	fmt.Println("looking for " + user + ", " + color + ", " + strconv.Itoa(size))

	//get the marble index
	marblesAsBytes, err := stub.GetState(marbleIndexStr)
	if err != nil {
		return fail, errors.New("Failed to get marble index")
	}
	var marbleIndex []string
	json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()

	for i := range marbleIndex { //iter through all the marbles
		//fmt.Println("looking @ marble name: " + marbleIndex[i]);

		marbleAsBytes, err := stub.GetState(marbleIndex[i]) //grab this marble
		if err != nil {
			return fail, errors.New("Failed to get marble")
		}
		res := Marble{}
		json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse()
		//fmt.Println("looking @ " + res.User + ", " + res.Color + ", " + strconv.Itoa(res.Size));

		//check for user && color && size
		if strings.ToLower(res.User) == strings.ToLower(user) && strings.ToLower(res.Color) == strings.ToLower(color) && res.Size == size {
			fmt.Println("found a marble: " + res.Name)
			fmt.Println("! end find marble 4 trade")
			return res, nil
		}
	}

	fmt.Println("- end find marble 4 trade - error")
	return fail, errors.New("Did not find marble to use in this trade")
}
開發者ID:IBM-Blockchain,項目名稱:marbles,代碼行數:38,代碼來源:marbles_chaincode.go

示例3: Query

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function != "query" {
		return nil, errors.New("Invalid query function name. Expecting \"query\"")
	}
	var A string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the person to query")
	}

	A = args[0]

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return Avalbytes, nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:30,代碼來源:chaincode_example02.go

示例4: Invoke

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function == "delete" {
		// Deletes an entity from its state
		return t.delete(stub, args)
	}

	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var X int          // Transaction value
	var err error

	if len(args) != 3 {
		return nil, errors.New("Incorrect number of arguments. Expecting 3")
	}

	A = args[0]
	B = args[1]

	// Get the state from the ledger
	// TODO: will be nice to have a GetAllState call to ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Avalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Aval, _ = strconv.Atoi(string(Avalbytes))

	Bvalbytes, err := stub.GetState(B)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Bvalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Bval, _ = strconv.Atoi(string(Bvalbytes))

	// Perform the execution
	X, err = strconv.Atoi(args[2])
	if err != nil {
		return nil, errors.New("Invalid transaction amount, expecting a integer value")
	}
	Aval = Aval - X
	Bval = Bval + X
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state back to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:61,代碼來源:chaincode_example02.go

示例5: delete

// delete Deletes an entity from the state, returning error if the entity was not found in the state.
func (t *Attributes2State) delete(stub shim.ChaincodeStubInterface, args []string) error {
	if len(args) != 1 {
		return errors.New("Incorrect number of arguments. Expecting only 1 (attributeName)")
	}

	attributeName := args[0]
	fmt.Printf("Deleting attribute %v", attributeName)
	valBytes, err := stub.GetState(attributeName)
	if err != nil {
		return err
	}

	if valBytes == nil {
		return errors.New("Attribute '" + attributeName + "' not found.")
	}

	isOk, err := stub.VerifyAttribute(attributeName, valBytes)
	if err != nil {
		return err
	}
	if isOk {
		// Delete the key from the state in ledger
		err = stub.DelState(attributeName)
		if err != nil {
			return errors.New("Failed to delete state")
		}
	}
	return nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:30,代碼來源:attributes_to_state.go

示例6: Delete

// ============================================================================================================================
// Delete - remove a key/value pair from state
// ============================================================================================================================
func (t *SimpleChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	name := args[0]
	err := stub.DelState(name) //remove the key from chaincode state
	if err != nil {
		return nil, errors.New("Failed to delete state")
	}

	//get the marble index
	marblesAsBytes, err := stub.GetState(marbleIndexStr)
	if err != nil {
		return nil, errors.New("Failed to get marble index")
	}
	var marbleIndex []string
	json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()

	//remove marble from index
	for i, val := range marbleIndex {
		fmt.Println(strconv.Itoa(i) + " - looking at " + val + " for " + name)
		if val == name { //find the correct marble
			fmt.Println("found marble")
			marbleIndex = append(marbleIndex[:i], marbleIndex[i+1:]...) //remove it
			for x := range marbleIndex {                                //debug prints...
				fmt.Println(string(x) + " - " + marbleIndex[x])
			}
			break
		}
	}
	jsonAsBytes, _ := json.Marshal(marbleIndex) //save new index
	err = stub.PutState(marbleIndexStr, jsonAsBytes)
	return nil, nil
}
開發者ID:IBM-Blockchain,項目名稱:marbles,代碼行數:38,代碼來源:marbles_chaincode.go

示例7: Invoke

// Invoke gets the supplied key and if it exists, updates the key with the newly
// supplied value.
func (t *SampleSysCC) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var key, val string // Entities

	if len(args) != 2 {
		return nil, errors.New("need 2 args (key and a value)")
	}

	// Initialize the chaincode
	key = args[0]
	val = args[1]

	_, err := stub.GetState(key)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get val for " + key + "\"}"
		return nil, errors.New(jsonResp)
	}

	// Write the state to the ledger
	err = stub.PutState(key, []byte(val))
	if err != nil {
		return nil, err
	}

	return nil, nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:27,代碼來源:samplesyscc.go

示例8: set_user

// ============================================================================================================================
// Set User Permission on Marble
// ============================================================================================================================
func (t *SimpleChaincode) set_user(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var err error

	//   0       1
	// "name", "bob"
	if len(args) < 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	fmt.Println("- start set user")
	fmt.Println(args[0] + " - " + args[1])
	marbleAsBytes, err := stub.GetState(args[0])
	if err != nil {
		return nil, errors.New("Failed to get thing")
	}
	res := Marble{}
	json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse()
	res.User = args[1]                  //change the user

	jsonAsBytes, _ := json.Marshal(res)
	err = stub.PutState(args[0], jsonAsBytes) //rewrite the marble with id as key
	if err != nil {
		return nil, err
	}

	fmt.Println("- end set user")
	return nil, nil
}
開發者ID:IBM-Blockchain,項目名稱:marbles,代碼行數:31,代碼來源:marbles_chaincode.go

示例9: Query

// Query callback representing the query of a chaincode
func (t *Attributes2State) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function != "read" {
		return nil, errors.New("Invalid query function name. Expecting \"read\"")
	}
	var attributeName string // Name of the attributeName to query.
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting only 1 (attributeName)")
	}

	attributeName = args[0]
	fmt.Printf("Reading attribute %v", attributeName)

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(attributeName)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + attributeName + "\"}"
		fmt.Printf("Query Response:%s\n", jsonResp)
		return nil, errors.New(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + attributeName + "\"}"
		fmt.Printf("Query Response:%s\n", jsonResp)
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + attributeName + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return []byte(jsonResp), nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:33,代碼來源:attributes_to_state.go

示例10: query

func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var event string // Event entity
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting entity to query")
	}

	event = args[0]

	// Get the state from the ledger
	eventValbytes, err := stub.GetState(event)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + event + "\"}"
		return nil, errors.New(jsonResp)
	}

	if eventValbytes == nil {
		jsonResp := "{\"Error\":\"Nil value for " + event + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + event + "\",\"Amount\":\"" + string(eventValbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return []byte(jsonResp), nil
}
開發者ID:hyperledger,項目名稱:fabric,代碼行數:26,代碼來源:chaincode_example04.go

示例11: Query

// Query function
func (t *EventSender) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	b, err := stub.GetState("noevents")
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	jsonResp := "{\"NoEvents\":\"" + string(b) + "\"}"
	return []byte(jsonResp), nil
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:9,代碼來源:eventsender.go

示例12: assign

func (t *AssetManagementChaincode) assign(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	fmt.Println("Assigning Asset...")

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	asset := args[0]
	owner, err := base64.StdEncoding.DecodeString(args[1])
	if err != nil {
		fmt.Printf("Error decoding [%v] \n", err)
		return nil, errors.New("Failed decodinf owner")
	}

	// Recover the role that is allowed to make assignments
	assignerRole, err := stub.GetState("assignerRole")
	if err != nil {
		fmt.Printf("Error getting role [%v] \n", err)
		return nil, errors.New("Failed fetching assigner role")
	}

	callerRole, err := stub.ReadCertAttribute("role")
	if err != nil {
		fmt.Printf("Error reading attribute 'role' [%v] \n", err)
		return nil, fmt.Errorf("Failed fetching caller role. Error was [%v]", err)
	}

	caller := string(callerRole[:])
	assigner := string(assignerRole[:])

	if caller != assigner {
		fmt.Printf("Caller is not assigner - caller %v assigner %v\n", caller, assigner)
		return nil, fmt.Errorf("The caller does not have the rights to invoke assign. Expected role [%v], caller role [%v]", assigner, caller)
	}

	account, err := attr.GetValueFrom("account", owner)
	if err != nil {
		fmt.Printf("Error reading account [%v] \n", err)
		return nil, fmt.Errorf("Failed fetching recipient account. Error was [%v]", err)
	}

	// Register assignment
	myLogger.Debugf("New owner of [%s] is [% x]", asset, owner)

	ok, err := stub.InsertRow("AssetsOwnership", shim.Row{
		Columns: []*shim.Column{
			&shim.Column{Value: &shim.Column_String_{String_: asset}},
			&shim.Column{Value: &shim.Column_Bytes{Bytes: account}}},
	})

	if !ok && err == nil {
		fmt.Println("Error inserting row")
		return nil, errors.New("Asset was already assigned.")
	}

	return nil, err
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:57,代碼來源:asset_management_with_roles.go

示例13: GetState

func (t *ChaincodeExample) GetState(stub shim.ChaincodeStubInterface, entity string) (int, error) {
	bytes, err := stub.GetState(entity)
	if err != nil {
		return 0, errors.New("Failed to get state")
	}
	if bytes == nil {
		return 0, errors.New("Entity not found")
	}

	val, _ := strconv.Atoi(string(bytes))
	return val, nil
}
開發者ID:hyperledger,項目名稱:fabric,代碼行數:12,代碼來源:chaincode_example02.go

示例14: Invoke

// Invoke gets the supplied key and if it exists, updates the key with the newly
// supplied value.
func (t *SampleSysCC) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) {
	f, args := stub.GetFunctionAndParameters()

	switch f {
	case "putval":
		if len(args) != 2 {
			return nil, errors.New("need 2 args (key and a value)")
		}

		// Initialize the chaincode
		key := args[0]
		val := args[1]

		_, err := stub.GetState(key)
		if err != nil {
			jsonResp := "{\"Error\":\"Failed to get val for " + key + "\"}"
			return nil, errors.New(jsonResp)
		}

		// Write the state to the ledger
		err = stub.PutState(key, []byte(val))
		return nil, err
	case "getval":
		var err error

		if len(args) != 1 {
			return nil, errors.New("Incorrect number of arguments. Expecting key to query")
		}

		key := args[0]

		// Get the state from the ledger
		valbytes, err := stub.GetState(key)
		if err != nil {
			jsonResp := "{\"Error\":\"Failed to get state for " + key + "\"}"
			return nil, errors.New(jsonResp)
		}

		if valbytes == nil {
			jsonResp := "{\"Error\":\"Nil val for " + key + "\"}"
			return nil, errors.New(jsonResp)
		}

		return valbytes, nil
	default:
		jsonResp := "{\"Error\":\"Unknown functon " + f + "\"}"
		return nil, errors.New(jsonResp)
	}
}
開發者ID:hyperledger,項目名稱:fabric,代碼行數:51,代碼來源:samplesyscc.go

示例15: read

// ============================================================================================================================
// Read - read a variable from chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var name, jsonResp string
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
	}

	name = args[0]
	valAsbytes, err := stub.GetState(name) //get the var from chaincode state
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	return valAsbytes, nil //send it onward
}
開發者ID:IBM-Blockchain,項目名稱:marbles,代碼行數:20,代碼來源:marbles_chaincode.go


注:本文中的github.com/hyperledger/fabric/core/chaincode/shim.ChaincodeStubInterface.GetState方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。