// ============================================================================================================================ // 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 }
// Query callback representing the query of a chaincode func (t *systemChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { if function != "query" { return nil, errors.New("Invalid query function name. Expecting \"query\"") } if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting 1") } key := args[0] if key != systemValidityPeriodKey { return nil, errors.New("Incorrect key. Expecting " + systemValidityPeriodKey) } // Get the state from the ledger vp, err := stub.GetState(key) if err != nil { jsonResp := "{\"Error\":\"Failed to get state for " + key + "\"}" return nil, errors.New(jsonResp) } if vp == nil { jsonResp := "{\"Error\":\"Nil value for " + key + "\"}" return nil, errors.New(jsonResp) } jsonResp := "{\"Name\":\"" + key + "\",\"Value\":\"" + string(vp) + "\"}" fmt.Printf("Query Response:%s\n", jsonResp) return []byte(jsonResp), nil }
//============================================================================================================================== // General Functions //============================================================================================================================== // get_ecert - Takes the name passed and calls out to the REST API for HyperLedger to retrieve the ecert // for that user. Returns the ecert as retrived including html encoding. //============================================================================================================================== func (t *SimpleChaincode) get_ecert(stub *shim.ChaincodeStub, name string) ([]byte, error) { var cert ECertResponse peer_address, err := stub.GetState("Peer_Address") if err != nil { return nil, errors.New("Error retrieving peer address") } response, err := http.Get("http://" + string(peer_address) + "/registrar/" + name + "/ecert") // Calls out to the HyperLedger REST API to get the ecert of the user with that name if err != nil { return nil, errors.New("Error calling ecert API") } defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) // Read the response from the http callout into the variable contents if err != nil { return nil, errors.New("Could not read body") } err = json.Unmarshal(contents, &cert) if err != nil { return nil, errors.New("Could not retrieve ecert for user: " + name) } return []byte(string(cert.OK)), 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 }
// ============================================================================================================================ // findMarble4Trade - look for a matching marble that this user owns and return it // ============================================================================================================================ func findMarble4Trade(stub *shim.ChaincodeStub, 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") }
func (t *SimpleChaincode) get_all_slots(stub *shim.ChaincodeStub, args []string) ([]byte, error) { slotsIndexBytes, err := stub.GetState(slotIndexStr) if err != nil { return nil, errors.New("Failed to get slots index") } var slotIndex []string err = json.Unmarshal(slotsIndexBytes, &slotIndex) if err != nil { return nil, errors.New("Could not marshal slot indexes") } var slots []Slot for _, slotId := range slotIndex { bytes, err := stub.GetState(slotId) if err != nil { return nil, errors.New("Not able to get slot") } var s Slot err = json.Unmarshal(bytes, &s) slots = append(slots, s) } slotsJson, err := json.Marshal(slots) if err != nil { return nil, errors.New("Failed to marshal slots to JSON") } return slotsJson, nil }
// Query callback representing the query of a chaincode func (t *SampleSysCC) Query(stub *shim.ChaincodeStub, 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 }
// 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 }
// "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 }
func (t *SimpleChaincode) get_all_devices(stub *shim.ChaincodeStub, args []string) ([]byte, error) { devicesIndexBytes, err := stub.GetState(deviceIndexStr) if err != nil { return nil, errors.New("Failed to get devices index") } var deviceIndex []string err = json.Unmarshal(devicesIndexBytes, &deviceIndex) if err != nil { return nil, errors.New("Could not marshal device indexes") } var devices []Device for _, deviceId := range deviceIndex { bytes, err := stub.GetState(deviceId) if err != nil { return nil, errors.New("Not able to get device") } var d Device err = json.Unmarshal(bytes, &d) devices = append(devices, d) } devicesJson, err := json.Marshal(devices) if err != nil { return nil, errors.New("Failed to marshal devices to JSON") } return devicesJson, nil }
func (t *SimpleChaincode) get_all_bids(stub *shim.ChaincodeStub, args []string) ([]byte, error) { bidIndexBytes, err := stub.GetState(bidIndexStr) if err != nil { return nil, errors.New("Failed to get bids index") } var bidIndex []string err = json.Unmarshal(bidIndexBytes, &bidIndex) if err != nil { return nil, errors.New("Could not marshal bid indexes") } var bids []Bid for _, bidId := range bidIndex { bytes, err := stub.GetState(bidId) if err != nil { return nil, errors.New("Not able to get bid") } var b Bid err = json.Unmarshal(bytes, &b) bids = append(bids, b) } bidsJson, err := json.Marshal(bids) if err != nil { return nil, errors.New("Failed to marshal bids to JSON") } return bidsJson, 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 }
// 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 // 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 }
func (t *SampleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) { if len(args) != 1 { return nil, errors.New("<name>") } return stub.GetState(args[0]) }
// Query function func (t *EventSender) Query(stub *shim.ChaincodeStub, 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 }
func (t *AssetManagementChaincode) assign(stub *shim.ChaincodeStub, 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 [%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 }
// 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 }
func (t *SimpleChaincode) get_account(stub *shim.ChaincodeStub, username string) ([]byte, error) { bytes, err := stub.GetState(username) if err != nil { return nil, errors.New("Could not retrieve information for this user") } return bytes, 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 }
//============================================================================================================================== // Query Functions //============================================================================================================================== // get_number - Retrieves the current number value stored in the world state and returns it // //============================================================================================================================== func (t *SimpleChaincode) get_number(stub *shim.ChaincodeStub, args []string) ([]byte, error) { bytes, err := stub.GetState("Number") if err != nil { return nil, errors.New("Unable to get number") } return bytes, nil }
func getTransactionById(stub *shim.ChaincodeStub, id string) (Transaction, []byte, error) { var transaction Transaction tsBytes, err := stub.GetState("transaction" + id) if err != nil { fmt.Println("Error retrieving cpBytes") } err = json.Unmarshal(tsBytes, &transaction) if err != nil { fmt.Println("Error unmarshalling centerBank") } return transaction, tsBytes, nil }
func getBankById(stub *shim.ChaincodeStub, id string) (Bank, []byte, error) { var bank Bank cbBytes, err := stub.GetState("bank" + id) if err != nil { fmt.Println("Error retrieving cpBytes") } err = json.Unmarshal(cbBytes, &bank) if err != nil { fmt.Println("Error unmarshalling centerBank") } return bank, cbBytes, nil }
func getCompanyById(stub *shim.ChaincodeStub, id string) (Company, []byte, error) { var company Company cpBytes, err := stub.GetState("company" + id) if err != nil { fmt.Println("Error retrieving cpBytes") } err = json.Unmarshal(cpBytes, &company) if err != nil { fmt.Println("Error unmarshalling centerBank") } return company, cpBytes, nil }
func getCenterBank(stub *shim.ChaincodeStub) (CenterBank, []byte, error) { var centerBank CenterBank cbBytes, err := stub.GetState("centerBank") if err != nil { fmt.Println("Error retrieving cbBytes") } err = json.Unmarshal(cbBytes, ¢erBank) if err != nil { fmt.Println("Error unmarshalling centerBank") } return centerBank, cbBytes, nil }
func getHomeByAddress(stub *shim.ChaincodeStub, address string) (Home,[]byte, error) { var home Home homeBytes,err := stub.GetState(address) if err != nil { fmt.Println("Error retrieving home") } err = json.Unmarshal(homeBytes, &home) if err != nil { fmt.Println("Error unmarshalling home") } return home,homeBytes, nil }
func(t *SimpleChaincode) getExpressOrderById(stub *shim.ChaincodeStub,id string)(ExpressOrder,[]byte,error){ var expressOrder ExpressOrder eoBytes,err := stub.GetState("expressOrder"+id) if err != nil{ fmt.Println("Error retrieving data") } err = json.Unmarshal(eoBygtes,&ExpessOrder) if err != nil{ fmt.Println("Error unmarshalling data") } return expressOrder,eoByes,nil }
func(t *SimpleChaincode) getExpress(stub *shim.ChaincodeStub)(Express,[]byte,error){ var express Express exBytes,err := stub.GetState("Express") if err != nil{ fmt.Println("Error retrieving data") } err = json.Unmarshal(exBytes,&express) if err != nil { fmt.Println("Error unmarshalling data") } return express,exBytes,nil }
func(t *SimpleChaincode) getUserByAddress(stub *shim.ChaincodeStub,address string)(User,[]byte,error){ var user User userBytes,err := stub.GetState(address) if err != nil{ fmt.Println("Error retrieving data") } err = json.Unmarshal(userBytes,&user) if err != nil { fmt.Println("Error unmarshalling data") } return user,userBytes,nil }
func(t *SimpleChaincode) getExpressPointerByAddress(stub *shim.ChaincodeStub,address string)(ExpressPointer,[]byte,error){ var expressPointer ExpressPointer epBytes,err := stub.GetState(address) if err != nil{ fmt.Println("Error retrieving data") } err = json.Unmarshal(epBytes,&expressPointer) if err != nil { fmt.Println("Error unmarshalling data") } return expressPointer,epBytes,nil }
// status implements the `status` query. If the -checkStatus flag was passed // as false, then we do not check for the array having been created, and we // assume that the length and count obtained from the state are correct. This // is a debug-only setting. func (c *counters) status(stub *shim.ChaincodeStub, args []string) (val []byte, err error) { c.debugf("status : Entry : checkStatus = %v", c.checkStatus) // Run down the list of arrays, pulling their state into our memory arrays := map[string][]uint64{} for _, name := range args { if c.checkStatus { if _, ok := c.length[name]; !ok { c.errorf("status : Array '%s' has never been created", name) } } b, err := stub.GetState(name) if err != nil { c.criticalf("status : GetState() for array '%s' failed : %s", name, err) } length := len(b) / 8 array := make([]uint64, length) arrays[name] = array err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &array) if err != nil { c.criticalf("status : Error converting %d bytes of array %s to uint64 : %s", len(b), name, err) } c.debugf("status : Array %s[%d] (%d bytes)", name, length, len(b)) } // Now create the result res := "" for _, name := range args { if res != "" { res += " " } actualLength := uint64(len(arrays[name])) actualCount := arrays[name][0] var expectedLength, expectedCount uint64 if c.checkStatus { expectedLength = c.length[name] expectedCount = c.count[name] } else { expectedLength = actualLength expectedCount = actualCount } res += fmt.Sprintf("%d %d %d %d", expectedLength, actualLength, expectedCount, actualCount) } c.debugf("status : Final status : %s", res) return []byte(res), nil }