// Init initialization func (t *AssetManagementChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { _, args := stub.GetFunctionAndParameters() 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{Name: "Asset", Type: shim.ColumnDefinition_STRING, Key: true}, &shim.ColumnDefinition{Name: "Owner", Type: shim.ColumnDefinition_BYTES, Key: false}, }) if err != nil { return nil, fmt.Errorf("Failed creating AssetsOnwership table, [%v]", err) } // 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() fmt.Printf("Assiger role is %v\n", string(assignerRole)) if err != nil { return nil, fmt.Errorf("Failed getting metadata, [%v]", err) } if len(assignerRole) == 0 { return nil, errors.New("Invalid assigner role. Empty.") } stub.PutState("assignerRole", assignerRole) return nil, nil }
//Init func will return error if function has string "error" anywhere func (p *PassthruChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { function, _ := stub.GetFunctionAndParameters() if strings.Index(function, "error") >= 0 { return nil, errors.New(function) } return []byte(function), nil }
// Init takes a string and int. These are stored as a key/value pair in the state func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { var A string // Entity var Aval int // Asset holding var err error _, args := stub.GetFunctionAndParameters() 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 }
// 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.ChaincodeStubInterface) ([]byte, error) { var sum string // Sum of asset holdings across accounts. Initially 0 var sumVal int // Sum of holdings var err error _, args := stub.GetFunctionAndParameters() 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 }
// Query callback representing the query of a chaincode // Supported functions are the following: // "query(asset)": returns the owner of the asset. // Anyone can invoke this function. func (t *AssetManagementChaincode) Query(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() myLogger.Debugf("Query [%s]", function) if function != "query" { return nil, errors.New("Invalid query function name. Expecting 'query' but found '" + function + "'") } var err error if len(args) != 1 { myLogger.Debug("Incorrect number of arguments. Expecting name of an asset to query") return nil, errors.New("Incorrect number of arguments. Expecting name of an asset to query") } // Who is the owner of the asset? asset := args[0] myLogger.Debugf("Arg [%s]", string(asset)) var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: asset}} columns = append(columns, col1) row, err := stub.GetRow("AssetsOwnership", columns) if err != nil { myLogger.Debugf("Failed retriving asset [%s]: [%s]", string(asset), err) return nil, fmt.Errorf("Failed retriving asset [%s]: [%s]", string(asset), err) } myLogger.Debugf("Query done [% x]", row.Columns[1].GetBytes()) return row.Columns[1].GetBytes(), nil }
// Invoke is a no-op func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() if function == "query" { return t.query(stub, args) } return nil, errors.New("Invalid invoke function name. Expecting \"query\"") }
// Init intializes the chaincode by reading the transaction attributes and storing // the attrbute values in the state func (t *Attributes2State) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { _, args := stub.GetFunctionAndParameters() err := t.setStateToAttributes(stub, args) if err != nil { return nil, err } return nil, nil }
// Invoke transaction makes payment of X units from A to B func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { _, args := stub.GetFunctionAndParameters() 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 []byte(fmt.Sprintf("{%d,%d}", Aval, Bval)), nil }
// Invoke method is the interceptor of all invocation transactions, its job is to direct // invocation transactions to intended APIs func (t *AuthorizableCounterChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() // Handle different functions if function == "increment" { return t.increment(stub, args) } else if function == "read" { return t.read(stub, args) } return nil, errors.New("Received unknown function invocation, Expecting \"increment\" \"read\"") }
// Init initialization, this method will create asset despository in the chaincode state func (t *AssetManagementChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() myLogger.Debugf("********************************Init****************************************") myLogger.Info("[AssetManagementChaincode] Init") if len(args) != 0 { return nil, errors.New("Incorrect number of arguments. Expecting 0") } return nil, dHandler.createTable(stub) }
func (t *Attributes2State) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() if function == "delete" { return nil, t.delete(stub, args) } else if function == "submit" { return nil, t.setStateToAttributes(stub, args) } else if function == "read" { return t.query(stub, args) } return nil, errors.New("Invalid invoke function name. Expecting either \"delete\" or \"submit\" or \"read\"") }
// Init method will be called during deployment func (t *RBACChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() // Init the crypto layer if err := crypto.Init(); err != nil { panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err)) } myLogger.Info("Init") // if len(args) != 0 { // return nil, errors.New("Incorrect number of arguments. Expecting 0") // } myLogger.Debug("Creating RBAC Table...") // Create RBAC table err := stub.CreateTable("RBAC", []*shim.ColumnDefinition{ &shim.ColumnDefinition{Name: "ID", Type: shim.ColumnDefinition_BYTES, Key: true}, &shim.ColumnDefinition{Name: "Roles", Type: shim.ColumnDefinition_STRING, Key: false}, }) if err != nil { return nil, errors.New("Failed creating RBAC table.") } myLogger.Debug("Assign 'admin' role...") // Give to the deployer the role 'admin' deployer, err := stub.GetCallerMetadata() if err != nil { return nil, errors.New("Failed getting metadata.") } if len(deployer) == 0 { return nil, errors.New("Invalid admin certificate. Empty.") } myLogger.Debug("Add admin [% x][%s]", deployer, "admin") ok, err := stub.InsertRow("RBAC", shim.Row{ Columns: []*shim.Column{ &shim.Column{Value: &shim.Column_Bytes{Bytes: deployer}}, &shim.Column{Value: &shim.Column_String_{String_: "admin"}}, }, }) if !ok && err == nil { return nil, fmt.Errorf("Failed initiliazing RBAC entries.") } if err != nil { return nil, fmt.Errorf("Failed initiliazing RBAC entries [%s]", err) } myLogger.Debug("Done.") return nil, nil }
// Invoke will be called for every transaction. // Supported functions are the following: // "assign(asset, owner)": to assign ownership of assets. An asset can be owned by a single entity. // Only an administrator can call this function. // "transfer(asset, newOwner)": to transfer the ownership of an asset. Only the owner of the specific // asset can call this function. // An asset is any string to identify it. An owner is representated by one of his ECert/TCert. func (t *AssetManagementChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() // Handle different functions if function == "assign" { // Assign ownership return t.assign(stub, args) } else if function == "transfer" { // Transfer ownership return t.transfer(stub, args) } return nil, errors.New("Received unknown function invocation") }
// Invoke Run callback representing the invocation of a chaincode func (t *RBACChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() // Handle different functions switch function { case "addRole": return t.addRole(stub, args) case "write": return t.write(stub, args) case "read": return t.read(stub, args) } return nil, fmt.Errorf("Received unknown function invocation [%s]", function) }
// 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) } }
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() if function == "invoke" { // Make payment of X units from A to B return t.invoke(stub, args) } else if function == "delete" { // Deletes an entity from its state return t.delete(stub, args) } else if function == "query" { // the old "Query" is now implemtned in invoke return t.query(stub, args) } return nil, errors.New("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"") }
// Invoke method is the interceptor of all invocation transactions, its job is to direct // invocation transactions to intended APIs func (t *AssetManagementChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() myLogger.Debugf("********************************Invoke****************************************") // Handle different functions if function == "assignOwnership" { // Assign ownership return t.assignOwnership(stub, args) } else if function == "transferOwnership" { // Transfer ownership return t.transferOwnership(stub, args) } else if function == "getOwnerContactInformation" { return t.getOwnerContactInformation(stub, args) } else if function == "getBalance" { return t.getBalance(stub, args) } return nil, errors.New("Received unknown function invocation") }
// Init method of chaincode func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { _, args := stub.GetFunctionAndParameters() 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 []byte("OK"), 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.ChaincodeStubInterface) ([]byte, error) { _, args := stub.GetFunctionAndParameters() 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 }
// Init takes two arguements, a string and int. These are stored in the key/value pair in the state func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) { var event string // Indicates whether event has happened. Initially 0 var eventVal int // State of event var err error _, args := stub.GetFunctionAndParameters() 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) err = stub.PutState(event, []byte(strconv.Itoa(eventVal))) if err != nil { return nil, err } return nil, nil }
// Invoke passes through the invoke call func (p *PassthruChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() return p.iq(stub, function, args) }
// Invoke callback representing the invocation of a chaincode // This chaincode will manage two accounts A and B and will transfer X units from A to B upon invoke func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() switch function { case "insertRowTableOne": if len(args) < 3 { return nil, errors.New("insertTableOne failed. Must include 3 column values") } col1Val := args[0] col2Int, err := strconv.ParseInt(args[1], 10, 32) if err != nil { return nil, errors.New("insertTableOne failed. arg[1] must be convertable to int32") } col2Val := int32(col2Int) col3Int, err := strconv.ParseInt(args[2], 10, 32) if err != nil { return nil, errors.New("insertTableOne failed. arg[2] must be convertable to int32") } col3Val := int32(col3Int) var columns []*shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} col2 := shim.Column{Value: &shim.Column_Int32{Int32: col2Val}} col3 := shim.Column{Value: &shim.Column_Int32{Int32: col3Val}} columns = append(columns, &col1) columns = append(columns, &col2) columns = append(columns, &col3) row := shim.Row{Columns: columns} ok, err := stub.InsertRow("tableOne", row) if err != nil { return nil, fmt.Errorf("insertTableOne operation failed. %s", err) } if !ok { return nil, errors.New("insertTableOne operation failed. Row with given key already exists") } case "insertRowTableTwo": if len(args) < 4 { return nil, errors.New("insertRowTableTwo failed. Must include 4 column values") } col1Val := args[0] col2Int, err := strconv.ParseInt(args[1], 10, 32) if err != nil { return nil, errors.New("insertRowTableTwo failed. arg[1] must be convertable to int32") } col2Val := int32(col2Int) col3Int, err := strconv.ParseInt(args[2], 10, 32) if err != nil { return nil, errors.New("insertRowTableTwo failed. arg[2] must be convertable to int32") } col3Val := int32(col3Int) col4Val := args[3] var columns []*shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} col2 := shim.Column{Value: &shim.Column_Int32{Int32: col2Val}} col3 := shim.Column{Value: &shim.Column_Int32{Int32: col3Val}} col4 := shim.Column{Value: &shim.Column_String_{String_: col4Val}} columns = append(columns, &col1) columns = append(columns, &col2) columns = append(columns, &col3) columns = append(columns, &col4) row := shim.Row{Columns: columns} ok, err := stub.InsertRow("tableTwo", row) if err != nil { return nil, fmt.Errorf("insertRowTableTwo operation failed. %s", err) } if !ok { return nil, errors.New("insertRowTableTwo operation failed. Row with given key already exists") } case "insertRowTableThree": if len(args) < 7 { return nil, errors.New("insertRowTableThree failed. Must include 7 column values") } col1Val := args[0] col2Int, err := strconv.ParseInt(args[1], 10, 32) if err != nil { return nil, errors.New("insertRowTableThree failed. arg[1] must be convertable to int32") } col2Val := int32(col2Int) col3Val, err := strconv.ParseInt(args[2], 10, 64) if err != nil { return nil, errors.New("insertRowTableThree failed. arg[2] must be convertable to int64") } col4Uint, err := strconv.ParseUint(args[3], 10, 32) if err != nil { return nil, errors.New("insertRowTableThree failed. arg[3] must be convertable to uint32") } col4Val := uint32(col4Uint) col5Val, err := strconv.ParseUint(args[4], 10, 64) if err != nil { return nil, errors.New("insertRowTableThree failed. arg[4] must be convertable to uint64") } col6Val := []byte(args[5]) col7Val, err := strconv.ParseBool(args[6]) if err != nil { return nil, errors.New("insertRowTableThree failed. arg[6] must be convertable to bool") } var columns []*shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} col2 := shim.Column{Value: &shim.Column_Int32{Int32: col2Val}} col3 := shim.Column{Value: &shim.Column_Int64{Int64: col3Val}} col4 := shim.Column{Value: &shim.Column_Uint32{Uint32: col4Val}} col5 := shim.Column{Value: &shim.Column_Uint64{Uint64: col5Val}} col6 := shim.Column{Value: &shim.Column_Bytes{Bytes: col6Val}} col7 := shim.Column{Value: &shim.Column_Bool{Bool: col7Val}} columns = append(columns, &col1) columns = append(columns, &col2) columns = append(columns, &col3) columns = append(columns, &col4) columns = append(columns, &col5) columns = append(columns, &col6) columns = append(columns, &col7) row := shim.Row{Columns: columns} ok, err := stub.InsertRow("tableThree", row) if err != nil { return nil, fmt.Errorf("insertRowTableThree operation failed. %s", err) } if !ok { return nil, errors.New("insertRowTableThree operation failed. Row with given key already exists") } case "insertRowTableFour": if len(args) < 1 { return nil, errors.New("insertRowTableFour failed. Must include 1 column value1") } col1Val := args[0] var columns []*shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, &col1) row := shim.Row{Columns: columns} ok, err := stub.InsertRow("tableFour", row) if err != nil { return nil, fmt.Errorf("insertRowTableFour operation failed. %s", err) } if !ok { return nil, errors.New("insertRowTableFour operation failed. Row with given key already exists") } case "deleteRowTableOne": if len(args) < 1 { return nil, errors.New("deleteRowTableOne failed. Must include 1 key value") } col1Val := args[0] var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) err := stub.DeleteRow("tableOne", columns) if err != nil { return nil, fmt.Errorf("deleteRowTableOne operation failed. %s", err) } case "replaceRowTableOne": if len(args) < 3 { return nil, errors.New("replaceRowTableOne failed. Must include 3 column values") } col1Val := args[0] col2Int, err := strconv.ParseInt(args[1], 10, 32) if err != nil { return nil, errors.New("replaceRowTableOne failed. arg[1] must be convertable to int32") } col2Val := int32(col2Int) col3Int, err := strconv.ParseInt(args[2], 10, 32) if err != nil { return nil, errors.New("replaceRowTableOne failed. arg[2] must be convertable to int32") } col3Val := int32(col3Int) var columns []*shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} col2 := shim.Column{Value: &shim.Column_Int32{Int32: col2Val}} col3 := shim.Column{Value: &shim.Column_Int32{Int32: col3Val}} columns = append(columns, &col1) columns = append(columns, &col2) columns = append(columns, &col3) row := shim.Row{Columns: columns} ok, err := stub.ReplaceRow("tableOne", row) if err != nil { return nil, fmt.Errorf("replaceRowTableOne operation failed. %s", err) } if !ok { return nil, errors.New("replaceRowTableOne operation failed. Row with given key does not exist") } case "deleteAndRecreateTableOne": err := stub.DeleteTable("tableOne") if err != nil { return nil, fmt.Errorf("deleteAndRecreateTableOne operation failed. Error deleting table. %s", err) } err = createTableOne(stub) if err != nil { return nil, fmt.Errorf("deleteAndRecreateTableOne operation failed. Error creating table. %s", err) } return nil, nil default: return nil, errors.New("Unsupported operation") } return nil, nil }
// Query callback representing the query of a chaincode func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() switch function { case "getRowTableOne": if len(args) < 1 { return nil, errors.New("getRowTableOne failed. Must include 1 key value") } col1Val := args[0] var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) row, err := stub.GetRow("tableOne", columns) if err != nil { return nil, fmt.Errorf("getRowTableOne operation failed. %s", err) } rowString := fmt.Sprintf("%s", row) return []byte(rowString), nil case "getRowTableTwo": if len(args) < 3 { return nil, errors.New("getRowTableTwo failed. Must include 3 key values") } col1Val := args[0] col2Int, err := strconv.ParseInt(args[1], 10, 32) if err != nil { return nil, errors.New("getRowTableTwo failed. arg[1] must be convertable to int32") } col2Val := int32(col2Int) col3Val := args[2] var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} col2 := shim.Column{Value: &shim.Column_Int32{Int32: col2Val}} col3 := shim.Column{Value: &shim.Column_String_{String_: col3Val}} columns = append(columns, col1) columns = append(columns, col2) columns = append(columns, col3) row, err := stub.GetRow("tableTwo", columns) if err != nil { return nil, fmt.Errorf("getRowTableTwo operation failed. %s", err) } rowString := fmt.Sprintf("%s", row) return []byte(rowString), nil case "getRowTableThree": if len(args) < 1 { return nil, errors.New("getRowTableThree failed. Must include 1 key value") } col1Val := args[0] var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) row, err := stub.GetRow("tableThree", columns) if err != nil { return nil, fmt.Errorf("getRowTableThree operation failed. %s", err) } rowString := fmt.Sprintf("%s", row) return []byte(rowString), nil case "getRowsTableTwo": if len(args) < 1 { return nil, errors.New("getRowsTableTwo failed. Must include at least key values") } var columns []shim.Column col1Val := args[0] col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) if len(args) > 1 { col2Int, err := strconv.ParseInt(args[1], 10, 32) if err != nil { return nil, errors.New("getRowsTableTwo failed. arg[1] must be convertable to int32") } col2Val := int32(col2Int) col2 := shim.Column{Value: &shim.Column_Int32{Int32: col2Val}} columns = append(columns, col2) } rowChannel, err := stub.GetRows("tableTwo", columns) if err != nil { return nil, fmt.Errorf("getRowsTableTwo operation failed. %s", err) } var rows []shim.Row for { select { case row, ok := <-rowChannel: if !ok { rowChannel = nil } else { rows = append(rows, row) } } if rowChannel == nil { break } } jsonRows, err := json.Marshal(rows) if err != nil { return nil, fmt.Errorf("getRowsTableTwo operation failed. Error marshaling JSON: %s", err) } return jsonRows, nil case "getRowTableFour": if len(args) < 1 { return nil, errors.New("getRowTableFour failed. Must include 1 key") } col1Val := args[0] var columns []shim.Column col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) row, err := stub.GetRow("tableFour", columns) if err != nil { return nil, fmt.Errorf("getRowTableFour operation failed. %s", err) } rowString := fmt.Sprintf("%s", row) return []byte(rowString), nil case "getRowsTableFour": if len(args) < 1 { return nil, errors.New("getRowsTableFour failed. Must include 1 key value") } var columns []shim.Column col1Val := args[0] col1 := shim.Column{Value: &shim.Column_String_{String_: col1Val}} columns = append(columns, col1) rowChannel, err := stub.GetRows("tableFour", columns) if err != nil { return nil, fmt.Errorf("getRowsTableFour operation failed. %s", err) } var rows []shim.Row for { select { case row, ok := <-rowChannel: if !ok { rowChannel = nil } else { rows = append(rows, row) } } if rowChannel == nil { break } } jsonRows, err := json.Marshal(rows) if err != nil { return nil, fmt.Errorf("getRowsTableFour operation failed. Error marshaling JSON: %s", err) } return jsonRows, nil default: return nil, errors.New("Unsupported operation") } }
// 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.ChaincodeStubInterface) ([]byte, error) { function, args := stub.GetFunctionAndParameters() 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 case "get": if len(args) < 1 { return nil, errors.New("get operation must include one argument, a key") } key := args[0] value, err := stub.GetState(key) if err != nil { return nil, fmt.Errorf("get operation failed. Error accessing state: %s", err) } return value, nil case "keys": keysIter, err := stub.RangeQueryState("", "") if err != nil { return nil, fmt.Errorf("keys operation failed. Error accessing state: %s", err) } defer keysIter.Close() var keys []string for keysIter.HasNext() { key, _, iterErr := keysIter.Next() if iterErr != nil { return nil, fmt.Errorf("keys operation failed. Error accessing state: %s", err) } keys = append(keys, key) } jsonKeys, err := json.Marshal(keys) if err != nil { return nil, fmt.Errorf("keys operation failed. Error marshaling JSON: %s", err) } return jsonKeys, nil default: return nil, errors.New("Unsupported operation") } }