本文整理匯總了Golang中github.com/hyperledger/fabric/core/chaincode/shim.ChaincodeStub.PutState方法的典型用法代碼示例。如果您正苦於以下問題:Golang ChaincodeStub.PutState方法的具體用法?Golang ChaincodeStub.PutState怎麽用?Golang ChaincodeStub.PutState使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/hyperledger/fabric/core/chaincode/shim.ChaincodeStub
的用法示例。
在下文中一共展示了ChaincodeStub.PutState方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: set_user
// ============================================================================================================================
// Set User Permission on Marble
// ============================================================================================================================
func (t *SimpleChaincode) set_user(stub *shim.ChaincodeStub, 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
}
示例2: Invoke
// Invoke gets the supplied key and if it exists, updates the key with the newly
// supplied value.
func (t *SampleSysCC) Invoke(stub *shim.ChaincodeStub, 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
}
示例3: Init
// Init takes two arguments, a string and int. The string will be a key with
// the int as a value.
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var sum string // Sum of asset holdings across accounts. Initially 0
var sumVal int // Sum of holdings
var err error
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
// Initialize the chaincode
sum = args[0]
sumVal, err = strconv.Atoi(args[1])
if err != nil {
return nil, errors.New("Expecting integer value for sum")
}
fmt.Printf("sumVal = %d\n", sumVal)
// Write the state to the ledger
err = stub.PutState(sum, []byte(strconv.Itoa(sumVal)))
if err != nil {
return nil, err
}
return nil, nil
}
示例4: add_number
//==============================================================================================================================
// Invoke Functions
//==============================================================================================================================
// add_number - Retrieves the current number value stored in the world state and adds a number passed by the invoker to it
// and updates Number to the new value in the world state
//==============================================================================================================================
func (t *SimpleChaincode) add_number(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
//Args
// 0
// Value to add
adder, _ := strconv.Atoi(args[0])
bytes, err := stub.GetState("Number")
if err != nil {
return nil, errors.New("Unable to get number")
}
number, _ := strconv.Atoi(string(bytes))
newNumber := number + adder
toPut := strconv.Itoa(newNumber)
err = stub.PutState("Number", []byte(toPut))
if err != nil {
return nil, errors.New("Unable to put the state")
}
return nil, nil
}
示例5: Init
//==============================================================================================================================
// Init Function - Called when the user deploys the chaincode sets up base vehicle_logs (blank array)
//==============================================================================================================================
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
//Args
// 0
// peer_address
var eh Vehicle_Log_Holder
bytes, err := json.Marshal(eh)
if err != nil {
return nil, errors.New("Error creating vehicle_log record")
}
err = stub.PutState("Vehicle_Logs", bytes)
if err != nil {
return nil, errors.New("Error creating blank vehicle_log array")
}
err = stub.PutState("Peer_Address", []byte(args[0]))
if err != nil {
return nil, errors.New("Error storing peer address")
}
return nil, nil
}
示例6: append_id
// "create": true -> create new ID, false -> append the id
func append_id(stub *shim.ChaincodeStub, indexStr string, id string, create bool) ([]byte, error) {
indexAsBytes, err := stub.GetState(indexStr)
if err != nil {
return nil, errors.New("Failed to get " + indexStr)
}
fmt.Println(indexStr + " retrieved")
// Unmarshal the index
var tmpIndex []string
json.Unmarshal(indexAsBytes, &tmpIndex)
fmt.Println(indexStr + " unmarshalled")
// Create new id
var newId = id
if create {
newId += strconv.Itoa(len(tmpIndex) + 1)
}
// append the new id to the index
tmpIndex = append(tmpIndex, newId)
jsonAsBytes, _ := json.Marshal(tmpIndex)
err = stub.PutState(indexStr, jsonAsBytes)
if err != nil {
return nil, errors.New("Error storing new " + indexStr + " into ledger")
}
return []byte(newId), nil
}
示例7: Init
// Init method will be called during deployment.
// The deploy transaction metadata is supposed to contain the administrator cert
func (t *AssetManagementChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
myLogger.Debug("Init Chaincode...")
if len(args) != 0 {
return nil, errors.New("Incorrect number of arguments. Expecting 0")
}
// Create ownership table
err := stub.CreateTable("AssetsOwnership", []*shim.ColumnDefinition{
&shim.ColumnDefinition{Name: "Asset", Type: shim.ColumnDefinition_STRING, Key: true},
&shim.ColumnDefinition{Name: "Owner", Type: shim.ColumnDefinition_BYTES, Key: false},
})
if err != nil {
return nil, errors.New("Failed creating AssetsOnwership table.")
}
// Set the admin
// The metadata will contain the certificate of the administrator
adminCert, err := stub.GetCallerMetadata()
if err != nil {
myLogger.Debug("Failed getting metadata")
return nil, errors.New("Failed getting metadata.")
}
if len(adminCert) == 0 {
myLogger.Debug("Invalid admin certificate. Empty.")
return nil, errors.New("Invalid admin certificate. Empty.")
}
myLogger.Debug("The administrator is [%x]", adminCert)
stub.PutState("admin", adminCert)
myLogger.Debug("Init Chaincode...done")
return nil, nil
}
示例8: Init
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var A, B string // Entities
var Aval, Bval int // Asset holdings
var err error
if len(args) != 4 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
// Initialize the chaincode
A = args[0]
Aval, err = strconv.Atoi(args[1])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
B = args[2]
Bval, err = strconv.Atoi(args[3])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)
// Write the state 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
}
示例9: Init
// ============================================================================================================================
// Init - reset all the things
// ============================================================================================================================
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
var Aval int
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
// Initialize the chaincode
Aval, err = strconv.Atoi(args[0])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
// Write the state to the ledger
err = stub.PutState("abc", []byte(strconv.Itoa(Aval))) //making a test var "abc", I find it handy to read/write to it right away to test the network
if err != nil {
return nil, err
}
var empty []string
jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index
err = stub.PutState(marbleIndexStr, jsonAsBytes)
if err != nil {
return nil, err
}
return nil, nil
}
示例10: Delete
// ============================================================================================================================
// Delete - remove a key/value pair from state
// ============================================================================================================================
func (t *SimpleChaincode) Delete(stub *shim.ChaincodeStub, 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
}
示例11: Invoke
// Invoke has two functions
// put - takes two arguements, a key and value, and stores them in the state
// remove - takes one argument, a key, and removes if from the state
func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
switch function {
case "put":
if len(args) < 2 {
return nil, errors.New("put operation must include two arguments, a key and value")
}
key := args[0]
value := args[1]
err := stub.PutState(key, []byte(value))
if err != nil {
fmt.Printf("Error putting state %s", err)
return nil, fmt.Errorf("put operation failed. Error updating state: %s", err)
}
return nil, nil
case "remove":
if len(args) < 1 {
return nil, errors.New("remove operation must include one argument, a key")
}
key := args[0]
err := stub.DelState(key)
if err != nil {
return nil, fmt.Errorf("remove operation failed. Error updating state: %s", err)
}
return nil, nil
default:
return nil, errors.New("Unsupported operation")
}
}
示例12: Init
func (t *AssetManagementChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
myLogger.Info("[AssetManagementChaincode] Init")
if len(args) != 0 {
return nil, errors.New("Incorrect number of arguments. Expecting 0")
}
// Create ownership table
err := stub.CreateTable("AssetsOwnership", []*shim.ColumnDefinition{
&shim.ColumnDefinition{"Asset", shim.ColumnDefinition_STRING, true},
&shim.ColumnDefinition{"Owner", shim.ColumnDefinition_BYTES, false},
})
if err != nil {
return nil, errors.New("Failed creating AssetsOnwership table.")
}
// Set the role of the users that are allowed to assign assets
// The metadata will contain the role of the users that are allowed to assign assets
assignerRole, err := stub.GetCallerMetadata()
if err != nil {
return nil, errors.New("Failed getting metadata.")
}
if len(assignerRole) == 0 {
return nil, errors.New("Invalid assigner role. Empty.")
}
stub.PutState("assignerRole", assignerRole)
return nil, nil
}
示例13: Query
// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
if function != "query" {
return nil, errors.New("Invalid query function name. Expecting \"query\"")
}
var A string // Entity
var Aval int // Asset holding
var err error
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
A = args[0]
Aval, err = strconv.Atoi(args[1])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
fmt.Printf("Aval = %d\n", Aval)
// Write the state to the ledger - this put is illegal within Run
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
jsonResp := "{\"Error\":\"Cannot put state within chaincode query\"}"
return nil, errors.New(jsonResp)
}
fmt.Printf("Something is wrong. This query should not have succeeded")
return nil, nil
}
示例14: Init
// Init function
func (t *EventSender) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
err := stub.PutState("noevents", []byte("0"))
if err != nil {
return nil, err
}
return nil, nil
}
示例15: Invoke
// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, 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])
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
}