func (t *SimpleChaincode) transfer(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var v Vehicle var err error var bytes []byte bytes, err = stub.GetState(args[0]) if err != nil { return nil, errors.New("Error retrieving vehicle with v5cID = " + args[0]) } err = json.Unmarshal(bytes, &v) if err != nil { return nil, errors.New("Corrupt vehicle record") } v.Owner = args[1] bytes, err = json.Marshal(v) if err != nil { return nil, errors.New("Error creating vehicle record") } err = stub.PutState(v.V5cID, bytes) if err != nil { return nil, err } return nil, nil }
// ============================================================================================================================ // Init - reset all the things // ============================================================================================================================ func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, 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 }
func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, args []string) ([]byte, error) { 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") } // 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") } fmt.Printf("Aval = %d\n", Aval) // Write the state to the ledger - this put is legal within Run err = stub.PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return nil, err } return nil, nil }
func (t *Vehicle) update_registration(stub *shim.ChaincodeStub, args []string) ([]byte, error) { regBytes, err := stub.GetState("Reg") reg := string(regBytes) if err != nil { return nil, errors.New("Failed to get state") } statusBytes, err := stub.GetState("Status") status, err := strconv.Atoi(string(statusBytes)) if err != nil { return nil, errors.New("Failed to get state") } if status == 1 || status == 2 { reg = args[0] } else { return nil, errors.New("Permission denied") } err = stub.PutState("Reg", []byte(reg)) return nil, nil }
// Initialize entities to random variables in order to test ledger status consensus func (t *SimpleChaincode) initRand(stub *shim.ChaincodeStub, 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 = rand.Intn(100) B = args[1] Bval = rand.Intn(100) 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 }
// ============================================================================================================================ // 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 }
func (t *Vehicle) update_model(stub *shim.ChaincodeStub, args []string) ([]byte, error) { modelBytes, err := stub.GetState("Model") model := string(modelBytes) if err != nil { return nil, errors.New("Failed to get state") } statusBytes, err := stub.GetState("Status") status, err := strconv.Atoi(string(statusBytes)) if err != nil { return nil, errors.New("Failed to get state") } ownerBytes, err := stub.GetState("Owner") owner := string(ownerBytes) if err != nil { return nil, errors.New("Failed to get state") } if status == 1 && owner == "Toyota" { model = args[0] } else { return nil, errors.New("Permission denied") } err = stub.PutState("Model", []byte(model)) return nil, nil }
func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var event string // Indicates whether event has happened. Initially 0 var eventVal int // State of event var err error if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } // Initialize the chaincode event = args[0] eventVal, err = strconv.Atoi(args[1]) if err != nil { return nil, errors.New("Expecting integer value for event status") } fmt.Printf("eventVal = %d\n", eventVal) // Write the state to the ledger err = stub.PutState(event, []byte(strconv.Itoa(eventVal))) if err != nil { return nil, err } 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 == "getstring" { return t.getstring(stub, args) } else 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 }
// ============================================================================================================================ // 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 }
func (t *AssetManagementChaincode) init(stub *shim.ChaincodeStub, 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 admin // The metadata will contain the certificate of the administrator adminCert, err := stub.GetCallerMetadata() if err != nil { return nil, errors.New("Failed getting metadata.") } if len(adminCert) == 0 { return nil, errors.New("Invalid admin certificate. Empty.") } stub.PutState("admin", adminCert) return nil, nil }
func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, 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 }
// ============================================================================================================================ // Init Car // ============================================================================================================================ func (t *SimpleChaincode) init_car(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var err error if len(args) != 5 { return nil, errors.New("Incorrect number of arguments. Expecting 5") } str := `{ "data": { "vin": "` + args[0] + `", "year": "` + args[1] + `" "make": "` + args[2] + `", "model": "` + args[3] + `", "license": "-" }, "users": [{ "userid": "` + args[4] + `", "permissions":["owner"] }] }` // Write the state back to the ledger err = stub.PutState(args[0], []byte(str)) //store car with vin# as key if err != nil { return nil, err } t.remember_me(stub, args[0]) return nil, nil }
// ============================================================================================================================ // Set User Permissions // ============================================================================================================================ func (t *SimpleChaincode) set_user_perms(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var err error carAsBytes, err := stub.GetState(args[0]) if err != nil { return nil, errors.New("Failed to get car profile") } res := Car{} json.Unmarshal(carAsBytes, &res) fmt.Println(res) for i, perm := range res.Users { if perm.UserId == args[1] { //find the correct user res.Users[i].Permissions[0] = args[2] //set new perm, dsh - to do make this input as array of all perms fmt.Println(res.Users[i].Permissions) break } } // Write the state back to the ledger jsonAsBytes, _ := json.Marshal(res) err = stub.PutState(args[0], jsonAsBytes) if err != nil { return nil, err } return nil, nil }
func (t *Vehicle) update_colour(stub *shim.ChaincodeStub, args []string) ([]byte, error) { colourBytes, err := stub.GetState("Colour") colour := string(colourBytes) if err != nil { return nil, errors.New("Failed to get state") } statusBytes, err := stub.GetState("Status") status, err := strconv.Atoi(string(statusBytes)) if err != nil { return nil, errors.New("Failed to get state") } if status == 1 || status == 2 { colour = args[0] } else { return nil, errors.New("Permission denied") } err = stub.PutState("Colour", []byte(colour)) return nil, nil }
func (t *Vehicle) scrap_merchant_to_scrap(stub *shim.ChaincodeStub, args []string) ([]byte, error) { statusBytes, err := stub.GetState("Status") status, err := strconv.Atoi(string(statusBytes)) if err != nil { return nil, errors.New("Failed to get state") } scrappedBytes, err := stub.GetState("Scrapped") scrapped, err := strconv.ParseBool(string(scrappedBytes)) if err != nil { return nil, errors.New("Failed to get state") } ownerBytes, err := stub.GetState("Owner") owner := string(ownerBytes) if err != nil { return nil, errors.New("Failed to get state") } if !scrapped && owner == "Cray Bros (London) Ltd" && status == 4 { scrapped = true } else { return nil, errors.New("Permission denied") } err = stub.PutState("Scrapped", []byte(strconv.FormatBool(scrapped))) return nil, nil }
func (t *Vehicle) lease_company_to_private(stub *shim.ChaincodeStub, args []string) ([]byte, error) { statusBytes, err := stub.GetState("Status") status, err := strconv.Atoi(string(statusBytes)) if err != nil { return nil, errors.New("Failed to get state") } ownerBytes, err := stub.GetState("Owner") owner := string(ownerBytes) if err != nil { return nil, errors.New("Failed to get state") } scrappedBytes, err := stub.GetState("Scrapped") scrapped, err := strconv.ParseBool(string(scrappedBytes)) if err != nil { return nil, errors.New("Failed to get state") } if status == 2 && owner == "LeaseCan" && !scrapped { owner = args[0] } else { return nil, errors.New("Permission denied") } err = stub.PutState("Owner", []byte(owner)) return nil, nil }
// Transaction queries another chaincode and updates its own state func (t *SimpleChaincode) invoke(stub *shim.ChaincodeStub, 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) != 3 { return nil, errors.New("Incorrect number of arguments. Expecting 3") } chaincodeUrl := args[0] // Expecting "github.com/openblockchain/obc-peer/openchain/example/chaincode/chaincode_example02" chaincodeVersion := args[1] // Expecting "0.0.1" sum = args[2] // Query chaincode_example02 f := "query" queryArgs := []string{"a"} response, err := stub.QueryChaincode(chaincodeUrl, chaincodeVersion, 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, chaincodeVersion, 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, 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 (t *SimpleChaincode) test(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var err error // Write the state back to the ledger str := "hey there" err = stub.PutState("test", []byte(str)) 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, args []string) ([]byte, error) { 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 Avalbytes == 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 }
// ============================================================================================================================ // Init TEST // ============================================================================================================================ func (t *SimpleChaincode) init_test(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var err error str := `{"userid": "test", "fullname": "mr test"}` // Write the state back to the ledger err = stub.PutState("test", []byte(str)) if err != nil { return nil, err } t.remember_me(stub, "test") return nil, nil }
//============================================================================================================================== // save_changes - Writes to the ledger the Vehicle struct passed in a JSON format. Uses the shim file's // method 'PutState'. //============================================================================================================================== func (t *Chaincode) save_changes(stub *shim.ChaincodeStub, v Vehicle) (bool, error) { bytes, err := json.Marshal(v) if err != nil { return false, errors.New("Error creating vehicle record") } err = stub.PutState(v.V5cID, bytes) if err != nil { return false, err } return true, nil }
// ============================================================================================================================ // Init TEST // ============================================================================================================================ func (t *SimpleChaincode) Test(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var err error fmt.Println("run Test - start") //str := "\"{\"userid\": \"test\", \"fullname\": \"mr test\"}" str := "what is going on here" // Write the state back to the ledger err = stub.PutState("test", []byte(str)) if err != nil { return nil, err } t.remember_me(stub, "test") fmt.Println("run Test - fin") return nil, nil }
// ============================================================================================================================ // Remember Me - remember the name of variables we stored in ledger // ============================================================================================================================ func (t *SimpleChaincode) remember_me(stub *shim.ChaincodeStub, name string) ([]byte, error) { //dsh - to do, should probably not exist here, move to stub var err error var ben = "_ben_knows" var storedNames string storeNamesAsBytes, err := stub.GetState(ben) if err != nil { return nil, errors.New("Failed to get ben") } storedNames = string(storeNamesAsBytes) // Write the state back to the ledger err = stub.PutState(ben, []byte(storedNames+","+name)) //dsh - to do, should probably be json if err != nil { return nil, err } return nil, nil }
func writeMortgageState(stub *shim.ChaincodeStub, state map[string]interface{}) ([]byte, error) { // Write updated state back to ledger bytes, err := json.Marshal(state) if err != nil { return bytes, err } //fmt.Printf("State: " + string(bytes) + "\n") fmt.Printf("Writing mortgage state to shared ledger...\n") err = stub.PutState("myMortgageState", bytes) if err != nil { return bytes, myError("Failed to write mortgage state to ledger") //return bytes, err } return bytes, nil }
// ============================================================================================================================ // Write - write variable into chaincode state // ============================================================================================================================ func (t *SimpleChaincode) Write(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var name, value string // Entities var err error fmt.Println("running write()") if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the variable and value to set") } name = args[0] //rename for funsies value = args[1] err = stub.PutState(name, []byte(value)) //write the variable into the chaincode state if err != nil { return nil, err } return nil, nil }
// Transaction invokes another chaincode and changes event state func (t *SimpleChaincode) invoke(stub *shim.ChaincodeStub, 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 }
//---------------------------------------------------------------------------------------------------------------------------------- // Write var into chaincode state func (t *SimpleChaincode) Write(stub *shim.ChaincodeStub, args []string) ([]byte, error) { var name string // Entities var err error if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting name of the variable and value to set") } name = args[0] // Write the state back to the ledger err = stub.PutState(name, []byte(args[1])) if err != nil { return nil, err } return nil, nil }