// ============================================================================================================================ // 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 }
// 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 }
// 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 }
//============================================================================================================================== // 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 }
//============================================================================================================================== // 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 }
// "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 }
// 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 }
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 }
// ============================================================================================================================ // 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 }
// ============================================================================================================================ // 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 }
// 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") } }
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 }
// 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 }
// 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 }
// 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 }
// Initialize the in the ledger (this needs to be run only once!!!!) func (t *systemChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { var vp int64 = 0 // ignore golint warning. Dropping '= 0' makes assignment less clear // Initialize the validity period in the ledger (this needs to be run only once!!!!) err := stub.PutState(systemValidityPeriodKey, []byte(strconv.FormatInt(vp, 10))) if err != nil { return nil, err } return nil, nil }
func(t *SimpleChaincode) writeExpress(stub *shim.ChaincodeStub,Express express)(error){ exBytes,err := json.Marshal(&express) if err != nil { return err } err = stub.PutState("Express", exBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
func writeHome(stub *shim.ChaincodeStub,home Home) (error) { homeBytes, err := json.Marshal(&home) if err != nil { return err } err = stub.PutState(home.Address, homeBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
// Invoke queries another chaincode and updates its own state func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { var sum string // Sum entity var Aval, Bval, sumVal int // value of sum entity - to be computed var err error if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } chaincodeURL := args[0] // Expecting "github.com/hyperledger/fabric/core/example/chaincode/chaincode_example02" sum = args[1] // Query chaincode_example02 f := "query" queryArgs := []string{"a"} response, err := stub.QueryChaincode(chaincodeURL, f, queryArgs) if err != nil { errStr := fmt.Sprintf("Failed to query chaincode. Got error: %s", err.Error()) fmt.Printf(errStr) return nil, errors.New(errStr) } Aval, err = strconv.Atoi(string(response)) if err != nil { errStr := fmt.Sprintf("Error retrieving state from ledger for queried chaincode: %s", err.Error()) fmt.Printf(errStr) return nil, errors.New(errStr) } queryArgs = []string{"b"} response, err = stub.QueryChaincode(chaincodeURL, f, queryArgs) if err != nil { errStr := fmt.Sprintf("Failed to query chaincode. Got error: %s", err.Error()) fmt.Printf(errStr) return nil, errors.New(errStr) } Bval, err = strconv.Atoi(string(response)) if err != nil { errStr := fmt.Sprintf("Error retrieving state from ledger for queried chaincode: %s", err.Error()) fmt.Printf(errStr) return nil, errors.New(errStr) } // Compute sum sumVal = Aval + Bval // Write sumVal back to the ledger err = stub.PutState(sum, []byte(strconv.Itoa(sumVal))) if err != nil { return nil, err } fmt.Printf("Invoke chaincode successful. Got sum %d\n", sumVal) return []byte(strconv.Itoa(sumVal)), nil }
// ============================================================================================================================ // Init Marble - create a new marble, store into chaincode state // ============================================================================================================================ func (t *SimpleChaincode) init_marble(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var err error // 0 1 2 3 // "asdf", "blue", "35", "bob" if len(args) != 4 { return nil, errors.New("Incorrect number of arguments. Expecting 4") } fmt.Println("- start init marble") if len(args[0]) <= 0 { return nil, errors.New("1st argument must be a non-empty string") } if len(args[1]) <= 0 { return nil, errors.New("2nd argument must be a non-empty string") } if len(args[2]) <= 0 { return nil, errors.New("3rd argument must be a non-empty string") } if len(args[3]) <= 0 { return nil, errors.New("4th argument must be a non-empty string") } size, err := strconv.Atoi(args[2]) if err != nil { return nil, errors.New("3rd argument must be a numeric string") } color := strings.ToLower(args[1]) user := strings.ToLower(args[3]) str := `{"name": "` + args[0] + `", "color": "` + color + `", "size": ` + strconv.Itoa(size) + `, "user": "******"}` err = stub.PutState(args[0], []byte(str)) //store marble with id as key if err != nil { return nil, err } //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() //append marbleIndex = append(marbleIndex, args[0]) //add marble name to index list fmt.Println("! marble index: ", marbleIndex) jsonAsBytes, _ := json.Marshal(marbleIndex) err = stub.PutState(marbleIndexStr, jsonAsBytes) //store name of marble fmt.Println("- end init marble") return nil, nil }
// Initialize the in the ledger (this needs to be run only once!!!!) func (t *systemChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { var vp int64 = 0 // Initialize the validity period in the ledger (this needs to be run only once!!!!) err := stub.PutState(system_validity_period_key, []byte(strconv.FormatInt(vp, 10))) if err != nil { return nil, err } return nil, nil }
func writeCenterBank(stub *shim.ChaincodeStub, centerBank CenterBank) error { cbBytes, err := json.Marshal(¢erBank) if err != nil { return err } err = stub.PutState("centerBank", cbBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
// Init resets all the things func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting 1") } err := stub.PutState("hello_world", []byte(args[0])) if err != nil { return nil, err } return nil, nil }
func(t *SimpleChaincode) writeExpressOrder(stub *shim.ChaincodeStub,ExpressOrder expressOrder)(error){ eoBytes,err := json.Marshal(&expressOrder) if err != nil { return err } id ,_:= strconv.Itoa(expressOrder.Id) err = stub.PutState("ExpressOrder"+id,eoBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
//============================================================================================================================== // Init Function - Called when the user deploys the chaincode sets up original number value, passed as an argument //============================================================================================================================== func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { //Args // 0 // start Number value err := stub.PutState("Number", []byte(args[0])) if err != nil { return nil, errors.New("INIT: Error putting state") } return nil, nil }
func writeTransaction(stub *shim.ChaincodeStub, transaction Transaction) error { var tsId string tsBytes, err := json.Marshal(&transaction) if err != nil { return err } tsId = strconv.Itoa(transaction.ID) if err != nil { return errors.New("want Integer number") } err = stub.PutState("transaction"+tsId, tsBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
func writeCompany(stub *shim.ChaincodeStub, company Company) error { var companyId string cpBytes, err := json.Marshal(&company) if err != nil { return err } companyId = strconv.Itoa(company.ID) if err != nil { return errors.New("want Integer number") } err = stub.PutState("company"+companyId, cpBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
func writeBank(stub *shim.ChaincodeStub, bank Bank) error { var bankId string bankBytes, err := json.Marshal(&bank) if err != nil { return err } bankId = strconv.Itoa(bank.ID) if err != nil { return errors.New("want Integer number") } err = stub.PutState("bank"+bankId, bankBytes) if err != nil { return errors.New("PutState Error" + err.Error()) } return nil }
// write - invoke function to write key/value pair func (t *SimpleChaincode) write(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var key, value string var err error fmt.Println("running write()") if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the key and value to set") } key = args[0] //rename for funsies value = args[1] err = stub.PutState(key, []byte(value)) //write the variable into the chaincode state if err != nil { return nil, err } return nil, nil }
// Invoke invokes another chaincode - chaincode_example02, upon receipt of an event and changes event state func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { var event string // Event entity var eventVal int // State of event var err error if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } event = args[0] eventVal, err = strconv.Atoi(args[1]) if err != nil { return nil, errors.New("Expected integer value for event state change") } if eventVal != 1 { fmt.Printf("Unexpected event. Doing nothing\n") return nil, nil } // Get the chaincode to call from the ledger chainCodeToCall, err := t.getChaincodeToCall(stub) if err != nil { return nil, err } f := "invoke" invokeArgs := []string{"a", "b", "10"} response, err := stub.InvokeChaincode(chainCodeToCall, f, invokeArgs) if err != nil { errStr := fmt.Sprintf("Failed to invoke chaincode. Got error: %s", err.Error()) fmt.Printf(errStr) return nil, errors.New(errStr) } fmt.Printf("Invoke chaincode successful. Got response %s", string(response)) // Write the event state back to the ledger err = stub.PutState(event, []byte(strconv.Itoa(eventVal))) if err != nil { return nil, err } return nil, nil }