error executing chaincode: failed to execute transaction: timeout expired while executing transaction - hyperledger-fabric

I write this chaincode and when I invoke it to read with GetOrgan the command is succeeded but when i want to add an organ with AddOrgan i have this error :
Error endorsing invoke: rpc error: code = Unknown desc = error executing >chaincode: failed to execute transaction: timeout expired while executing >transaction -
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
type SmartContract struct {
}
type Organ struct {
ID string `json:"ID"`
Type string `json:"type"`
Timestamp string `json:"timestamp"`
HolderHospital string `json:"HolderHospital"`
LifeSpan string `json:"LifeSpan"`
}
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface)
sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIstub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the
ledger
if function == "GetOrgan" {
return s.GetOrgan(APIstub, args)
} else if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "AddOrgan" {
return s.AddOrgan(APIstub, args)
} else if function == "GetAllOrgan" {
return s.GetAllOrgan(APIstub)
} else if function == "changeOrganHolder" {
return s.changeOrganHolder(APIstub, args)
}
return shim.Error("InvalID Smart Contract function name.")
}
func (s *SmartContract) GetOrgan(APIstub shim.ChaincodeStubInterface,
args []string) sc.Response {
fmt.println("hello from Chaincode")
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
organAsBytes, _ := APIstub.GetState(args[0])
if organAsBytes == nil {
return shim.Error("Could not locate organ")
}
return shim.Success(organAsBytes)
}
/*
* The initLedger method *
Will add test data (10 organ catches)to our network
*/
func (s *SmartContract) initLedger(APIstub
shim.ChaincodeStubInterface)
sc.Response {
fmt.println("hello from Chaincode")
organ := []Organ{
Organ{ID: "1", Type: "Foie", Timestamp: "12022003",
HolderHospital: "nabeul", LifeSpan: "24"},
Organ{ID: "2", Type: "Coeur", Timestamp: "12022003",
HolderHospital: "Tunis", LifeSpan: "36"},
}
i := 0
for i < len(organ) {
fmt.Println("i is ", i)
organAsBytes, _ := json.Marshal(organ[i])
APIstub.PutState(strconv.Itoa(i+1), organAsBytes)
fmt.Println("Added", organ[i])
i = i + 1
}
return shim.Success(nil)
}
func (s *SmartContract) AddOrgan(APIstub shim.ChaincodeStubInterface,
args []string) sc.Response {
fmt.println("hello from Chaincode")
if len(args) != 6 {
return shim.Error("Incorrect number of arguments. Expecting 6")
}
var organ = Organ{ID: args[1], Type: args[2], Timestamp: args[3],
HolderHospital: args[4], LifeSpan: args[5]}
organAsBytes, _ := json.Marshal(organ)
err := APIstub.PutState(args[0], organAsBytes)
if err != nil {
return shim.Error(fmt.Sprintf("Failed to add organ: %s", args[0]))
}
fmt.Print(err)
return shim.Success(nil)
}

Related

How to split string two between characters

I want to split a string up between two characters( {{ and }} ).
I have an string like {{number1}} + {{number2}} > {{number3}}
and I'm looking for something that returns:
[number1, number2, number3]
You can try it with Regex:
s := "{{number1}} + {{number2}} > {{number3}}"
// Find all substrings in form {<var name>}
re := regexp.MustCompile("{[a-z]*[0-9]*[a-z]*}")
nums := re.FindAllString(s, -1)
// Remove '{' and '}' from all substrings
for i, _ := range nums {
nums[i] = strings.TrimPrefix(nums[i], "{")
nums[i] = strings.TrimSuffix(nums[i], "}")
}
fmt.Println(nums) // output: [number1 number2 number3]
You can experiment with regex here: https://regex101.com/r/kkPWAS/1
Use the regex [A-Za-z]+[0-9] and filter the alpha numeric parts of the string as string array.
package main
import (
"fmt"
"regexp"
)
func main() {
s := `{{number1}} + {{number2}} > {{number3}}`
re := regexp.MustCompile("[A-Za-z]+[0-9]")
p := re.FindAllString(s, -1)
fmt.Println(p) //[number1 number2 number3]
}
the hard way using the template parser ^^
package main
import (
"fmt"
"strings"
"text/template/parse"
)
func main() {
input := "{{number1}} + {{number2}} > {{number3}}"
out := parseit(input)
fmt.Printf("%#v\n", out)
}
func parseit(input string) (out []string) {
input = strings.Replace(input, "{{", "{{.", -1) // Force func calls to become variables.
tree, err := parse.Parse("", input, "{{", "}}")
if err != nil {
panic(err)
}
visit(tree[""].Root, func(n parse.Node) bool {
x, ok := n.(*parse.FieldNode)
if ok {
out = append(out, strings.Join(x.Ident, "."))
}
return true
})
return
}
func visit(n parse.Node, fn func(parse.Node) bool) bool {
if n == nil {
return true
}
if !fn(n) {
return false
}
if l, ok := n.(*parse.ListNode); ok {
for _, nn := range l.Nodes {
if !visit(nn, fn) {
continue
}
}
}
if l, ok := n.(*parse.RangeNode); ok {
if !visit(l.BranchNode.Pipe, fn) {
return false
}
if l.BranchNode.List != nil {
if !visit(l.BranchNode.List, fn) {
return false
}
}
if l.BranchNode.ElseList != nil {
if !visit(l.BranchNode.ElseList, fn) {
return false
}
}
}
if l, ok := n.(*parse.ActionNode); ok {
for _, c := range l.Pipe.Decl {
if !visit(c, fn) {
continue
}
}
for _, c := range l.Pipe.Cmds {
if !visit(c, fn) {
continue
}
}
}
if l, ok := n.(*parse.CommandNode); ok {
for _, a := range l.Args {
if !visit(a, fn) {
continue
}
}
}
if l, ok := n.(*parse.PipeNode); ok {
for _, a := range l.Decl {
if !visit(a, fn) {
continue
}
}
for _, a := range l.Cmds {
if !visit(a, fn) {
continue
}
}
}
return true
}
If it happens you really were manipulating template string, but fails to do so due to function calls and that you do not want to execute this input = strings.Replace(input, "{{", "{{.", -1) // Force func calls to become variables.
You can always force load a template using functions similar to
var reMissingIdent = regexp.MustCompile(`template: :[0-9]+: function "([^"]+)" not defined`)
func ParseTextTemplateAnyway(s string) (*texttemplate.Template, texttemplate.FuncMap, error) {
fn := texttemplate.FuncMap{}
for {
t, err := texttemplate.New("").Funcs(fn).Parse(s)
if err == nil {
return t, fn, err
}
s := err.Error()
res := reMissingIdent.FindAllStringSubmatch(s, -1)
if len(res) > 0 {
fn[res[0][1]] = func(s ...interface{}) string { return "" }
} else {
return t, fn, err
}
}
// return nil, nil
}
You don't need to use libraries. You can create your own function.
package main
const r1 = '{'
const r2 = '}'
func GetStrings(in string) (out []string) {
var tren string
wr := false
f := true
for _, c := range in {
if wr && c != r2 {
tren = tren + string(c)
}
if c == r1 {
f = !f
wr = f
}
if c == r2 {
wr = false
if f {
out = append(out, tren)
tren = ""
}
f = !f
}
}
return
}

unexpected EOF with fmt.Scanner

If I want to scan through a string, I can do this:
package main
import (
"fmt"
"strings"
)
func main() {
r := strings.NewReader("west north east")
for {
var s string
_, e := fmt.Fscan(r, &s)
fmt.Printf("%q %v\n", s, e)
if e != nil { break }
}
}
Result:
"west" <nil>
"north" <nil>
"east" <nil>
"" EOF
I recently discovered fmt.Scanner [1], so I thought I would try to implement
it. I came up with this:
package main
import (
"fmt"
"strings"
)
type comma struct { tok string }
func (c *comma) Scan(state fmt.ScanState, verb rune) error {
tok, err := state.Token(false, func(r rune) bool {
return r != ','
})
if err != nil {
return err
}
if _, _, err := state.ReadRune(); err != nil {
if len(tok) == 0 {
return err
}
}
c.tok = string(tok)
return nil
}
func main() {
r := strings.NewReader("west,north,east")
for {
var c comma
_, e := fmt.Fscan(r, &c)
fmt.Printf("%q %v\n", c.tok, e)
if e != nil { break }
}
}
Result:
"west" <nil>
"north" <nil>
"east" <nil>
"" unexpected EOF
So the result is pretty close, but what bothers me is the unexpected EOF. Is
it possible to just get a regular EOF with a custom fmt.Scanner? Am I doing
something wrong here, or is this a bug?
https://golang.org/pkg/fmt#Scanner
Thanks to Ian Lance Taylor on the golang-nuts list, he suggested to panic
the error instead of return. In the Go code, Fscan calls a function
doScan, which in turn calls a function errorHandler [1]. This last function
uses recover to turn any panic into regular error. This program gives
idential output to my original example:
package main
import (
"fmt"
"strings"
)
type comma struct { tok string }
func (c *comma) Scan(state fmt.ScanState, verb rune) error {
tok, err := state.Token(false, func(r rune) bool {
return r != ','
})
if err != nil { return err }
if _, _, err := state.ReadRune(); err != nil {
if len(tok) == 0 {
panic(err)
}
}
c.tok = string(tok)
return nil
}
func main() {
r := strings.NewReader("west,north,east")
for {
var c comma
_, err := fmt.Fscan(r, &c)
fmt.Printf("%q %v\n", c.tok, err)
if err != nil { break }
}
}
https://github.com/golang/go/blob/go1.16.4/src/fmt/scan.go#L1056-L1067

uint8 to literal string representation

I'm trying to access the HackerNews API endpoint with a given ID 22024283 which represents a particular news item e.g https://hacker-news.firebaseio.com/v0/22024283.json
This itemID is of type uint8and I need to convert this to it's string representation to insert into the URL.
I cannot use strconv.Itoa(int(id)) as that will produce the number 91 and not preserve 22024283.
Any help on this would be appreciated. Here is my code so far, function of interest is GetHackerNewsItem():
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
//Client represents connection to firebase datastore
type Client struct {
BASEURI string
Version string
Suffix string
}
type Item struct {
id int `json:"id"`
itemtype string `json:"itemtype"`
by string `json:"by"`
time time.Time `json:"time"`
kids []int `json:"kids"`
url string `json:"url"`
score int `json:"score"`
text string `json:"text"`
title string `json:"title"`
descendants int `json:"descendants"`
}
//Connect to firebase datastore
func NewHackerNewsClient() *Client {
var client Client
client.BASEURI = "https://hacker-news.firebaseio.com/"
client.Version = "v0"
client.Suffix = ".json"
return &client
}
func MakeHTTPRequest(url string) ([]byte, error) {
response, err := http.Get(url)
if err != nil {
fmt.Printf("The http request failed with the error %s\n", err)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("Failed to read response data with the error %s\n", err)
return nil, err
}
return body, nil
}
func (client *Client) GetHackerNewsItem(id uint8) []byte {
itemID := strconv.Itoa(int(id))
fmt.Printf(itemID)
url := client.BASEURI + client.Version + itemID + client.Suffix
fmt.Printf(url)
item, _ := MakeHTTPRequest(url)
fmt.Print(item)
return item
}
func (client *Client) GetTopStories() {
url := client.BASEURI + client.Version + "/topstories/" + client.Suffix
itemArray, _ := MakeHTTPRequest(url)
for i := 0; i < len(itemArray); i++ {
item := client.GetHackerNewsItem(itemArray[i])
fmt.Print(item)
}
}
func main() {
client := NewHackerNewsClient()
client.GetTopStories()
}
itemArray, _ := MakeHTTPRequest(url)
itemArray must be unmarshaled like
dat := make([]uint64, 0)
if err := json.Unmarshal(itemArray, &dat); err != nil {
panic(err)
}

Getting "runtime error: invalid memory address or nil pointer dereference" when querying the chaincode

I'm using fabric-sdk-go to install, instantiate, invoke and querying the chaincode.
chaincode installation is successful.
root#991bc7577959:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer chaincode list --installed
Get installed chaincodes on peer:
Name: myproject, Version: 1.0, Path: github.com/hyperledger/myproject/chaincode/, Id: 130607a18ab3fe332854d7c2048f04b89e3c740e1ffa97c76c9ced266e6714ca
chaincode instantiation.
Snippet of code
ccPolicy := cauthdsl.SignedByAnyMember([]string{"Seller", "Buyer"})
fmt.Println("Value of ccPolicy is: ", ccPolicy)
resp, err := setup.admin.InstantiateCC(setup.ChannelID,
resmgmt.InstantiateCCRequest{
Name: setup.ChainCodeID,
Path: setup.ChaincodeGoPath,
Version: "1.0",
Args: [][]byte{[]byte("init"), []byte("Seller"), []byte("100"), []byte("Buyer"), []byte("200")},
Policy: ccPolicy,
})
checking the docker container
root#991bc7577959:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer chaincode list --instantiated -C mychannel
Get instantiated chaincodes on channel mychannel:
Name: myproject, Version: 1.0, Path: github.com/hyperledger/myproject/chaincode/, Input: <nil>, Escc: escc, Vscc: vscc
Here the chaincode is instantiated but the Input tag is showing nil value. Is it expected? Isn't it suppose to show the values that I've used for instantiation
Querying the chaincode
snippet of code
func (setup *FabricSetup) Query(OrgName string) (string, error) {
fmt.Println("\n Calling query method")
// Prepare arguments
var args []string
args = append(args, OrgName)
response, err := setup.client.Query(channel.Request{
ChaincodeID: setup.ChainCodeID,
Fcn: "invoke",
Args: [][]byte{[]byte("query"), []byte(args[0])}})
if err != nil {
return "", fmt.Errorf("failed to query: %v", err)
}
fmt.Println("\n Query chaincode ended")
return string(response.Payload), err
}
this querying of chaincode is resulting in below error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x9e17e0]
goroutine 1 [running]:
github.com/hyperledger/fabric-sdk-go/pkg/client/channel.(*Client).Query(0x0, 0xdb43d4, 0x9, 0xdb14ef, 0x6, 0xc00016ff80, 0x2, 0x2, 0x0, 0x0, ...)
/home/alpha/GoWorkspace/src/github.com/hyperledger/fabric-sdk-go/pkg/client/channel/chclient.go:97 +0xc0
github.com/hyperledger/myproject/sdk.(*FabricSetup).Query(0xc000179ea8, 0xdb0f3d, 0x6, 0x0, 0xdbbe50, 0x13, 0xdb43cb) >/home/alpha/GoWorkspace/src/github.com/hyperledger/myproject/sdk/query.go:17 +0x2d4
main.main()
/c/Projects/Go/src/github.com/hyperledger/myproject/main.go:79 +0x176
setup.go: file for creating a channel, installing and instantiating chaincode
import packages
type FabricSetup struct {
ConfigFile string
OrgID string
OrdererID string
ChannelID string
ChainCodeID string
initialized bool
ChannelConfig string
ChaincodeGoPath string
ChaincodePath string
OrgAdmin string
OrgName string
UserName string
client *channel.Client
admin *resmgmt.Client
adminIdentity *msp.SigningIdentity
sdk *fabsdk.FabricSDK
event *event.Client
}
// Initialize reads the configuration file and sets up the client, chain and event hub
func (setup *FabricSetup) Initialize() error {
// Step 1: creates the channel and updates all of the anchor peers for all orgs
identityManagerClientContext := setup.sdk.Context(fabsdk.WithUser(setup.OrgAdmin), fabsdk.WithOrg(setup.OrgName))
if err != nil {
return errors.WithMessage(err, "failed to load Admin identity")
}
fmt.Printf("\n Step 2.a: Value of identityManagerClientContext is: ", identityManagerClientContext)
// Channel management client is responsible for managing channels (create/update channel)
chMgmtClient, err := resmgmt.New(identityManagerClientContext)
if err != nil {
return errors.WithMessage(err, "failed to create channel management client from Admin identity")
}
setup.admin = chMgmtClient
mspClient, err := mspclient.New(setup.sdk.Context(), mspclient.WithOrg(setup.OrgName))
if err != nil {
return errors.WithMessage(err, "failed to create MSP client")
}
adminIdentity, err := mspClient.GetSigningIdentity(setup.OrgAdmin)
if err != nil {
return errors.WithMessage(err, "failed to get admin signing identity")
}
setup.adminIdentity = &adminIdentity
fmt.Println("Initialization Successful")
setup.initialized = true
return nil
}
// CreateChannel for creating channel between the Organizations
func (setup *FabricSetup) CreateChannel() error {
req := resmgmt.SaveChannelRequest{
ChannelID: setup.ChannelID,
ChannelConfigPath: setup.ChannelConfig,
SigningIdentities: []msp.SigningIdentity{*setup.adminIdentity},
}
txID, err := setup.admin.SaveChannel(req, resmgmt.WithOrdererEndpoint(setup.OrdererID))
if err != nil || txID.TransactionID == "" {
return errors.WithMessage(err, "failed to save channel")
}
fmt.Println("Channel created")
return nil
}
// joins all peers in all of the given orgs to the given channel
func (setup *FabricSetup) JoinChannel() error {
// Make admin user join the previously created channel
if err := setup.admin.JoinChannel(
setup.ChannelID,
resmgmt.WithRetry(retry.DefaultResMgmtOpts),
resmgmt.WithOrdererEndpoint(setup.OrdererID)); err != nil {
return errors.WithMessage(err, "failed to make admin join channel")
}
fmt.Println("Channel joined")
return nil
}
// InstallCC to install and instantiate the chaincode
func (setup *FabricSetup) InstallCC() error {
// Create the chaincode package that will be sent to the peers
ccPkg, err := packager.NewCCPackage(setup.ChaincodePath, setup.ChaincodeGoPath)
if err != nil {
return errors.WithMessage(err, "failed to create chaincode package")
}
fmt.Println("ccPkg created")
// Install example cc to org peers
installCCReq := resmgmt.InstallCCRequest{
Name: setup.ChainCodeID,
Path: setup.ChaincodePath,
Version: "1.0", //chaincode version. first version of chaincode
Package: ccPkg,
}
_, err = setup.admin.InstallCC(installCCReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts))
if err != nil {
return errors.WithMessage(err, "failed to install chaincode")
}
fmt.Println("Chaincode installed")
return nil
}
// InstantiateCC for instantiating the chaincode
func (setup *FabricSetup) InstantiateCC() error {
// Set up chaincode policy
ccPolicy := cauthdsl.SignedByAnyMember([]string{"Seller", "Buyer"})
fmt.Println("Value of ccPolicy is: ", ccPolicy)
resp, err := setup.admin.InstantiateCC(setup.ChannelID, resmgmt.InstantiateCCRequest{
Name: setup.ChainCodeID,
Path: setup.ChaincodeGoPath,
Version: "1.0",
Args: [][]byte{[]byte("init"), []byte("Seller"), []byte("100"), []byte("Buyer"), []byte("200")},
//Args: [][]byte{[]byte("init")},
Policy: ccPolicy,
})
if err != nil || resp.TransactionID == "" {
return errors.WithMessage(err, "failed to instantiate the chaincode")
}
fmt.Println("Chaincode instantiated")
// Channel client is used to query and execute transactions
clientContext := setup.sdk.ChannelContext(setup.ChannelID, fabsdk.WithUser(setup.UserName))
setup.client, err = channel.New(clientContext)
if err != nil {
return errors.WithMessage(err, "failed to create new channel client")
}
fmt.Println("Channel client created")
// Creation of the client which will enables access to our channel events
setup.event, err = event.New(clientContext)
if err != nil {
return errors.WithMessage(err, "failed to create new event client")
}
fmt.Println("Event client created")
fmt.Println("Chaincode Installation & Instantiation Successful")
return nil
}
// CloseSDK to close the sdk connection
func (setup *FabricSetup) CloseSDK() {
setup.sdk.Close()
}
main.go file: calling all the methods in this file
func initializeChannelAndCC(fSetup sdk.FabricSetup) {
err := fSetup.CreateChannel()
if err != nil {
fmt.Printf("Unable to create channel: %v\n", err)
}
err = fSetup.JoinChannel()
if err != nil {
fmt.Printf("Unable to join channel: %v\n", err)
}
err = fSetup.InstallCC()
if err != nil {
fmt.Printf("Unable to install the chaincode: %v\n", err)
}
err = fSetup.InstantiateCC()
if err != nil {
fmt.Printf("Unable to instantiate the chaincode: %v\n", err)
}
}
func main() {
fSetup := sdk.FabricSetup{
OrdererID: "orderer.mytrade.com",
ChannelID: "mychannel",
ChannelConfig: "/c/Projects/Go/src/github.com/hyperledger/myproject/network/channel-artifacts/channel.tx",
ChainCodeID: "myproject",
ChaincodeGoPath: "/c/Projects/Go",
ChaincodePath: "github.com/hyperledger/myproject/chaincode/",
OrgAdmin: "Admin",
OrgName: "Seller",
ConfigFile: "config.yaml",
UserName: "User1",
}
err := fSetup.Initialize()
if err != nil {
fmt.Printf("Unable to initialize the Fabric SDK: %v\n", err)
return
}
defer fSetup.CloseSDK()
initializeChannelAndCC(fSetup)
response, err := fSetup.Query("Seller")
if err != nil {
fmt.Printf("Unable to query the chaincode: %v\n", err)
} else {
fmt.Printf("Response from the query: %s\n", response)
}
}
client-side logging(set to debug mode). These logs are huge hence sharing the link ClientLogs
Please help.
EDIT: added chaincode
type SimpleChaincode struct {
}
// Init method: one time initialisation
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("ex02 Init")
_, args := stub.GetFunctionAndParameters()
var A, B string // Entities
var Aval, Bval int // Asset holdings
var err error
if len(args) != 4 {
return shim.Error("Incorrect number of arguments. Expecting 4")
}
test := strings.Join(args, ", ")
fmt.Println("Value of args is: ", test)
// Initialize the chaincode
A = args[0]
Aval, err = strconv.Atoi(args[1])
if err != nil {
return shim.Error("Expecting integer value for asset holding")
}
B = args[2]
Bval, err = strconv.Atoi(args[3])
if err != nil {
return shim.Error("Expecting integer value for asset holding")
}
fmt.Printf("A = %s, Aval = %d, B = %s, Bval = %d\n", A, Aval, B, Bval)
// Write the state to the ledger
err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
if err != nil {
return shim.Error(err.Error())
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
// Invoke method: used to sedn the request to the various custom methods
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("ex02 Invoke")
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 shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")
}
// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {
var A, B string // Entities
var Aval, Bval int // Asset holdings
var X int // Transaction value
var err error
fmt.Println("Value of args in invoke is: ", strings.Join(args, ", "))
if len(args) != 3 {
return shim.Error("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 shim.Error("Failed to get state")
}
if Avalbytes == nil {
return shim.Error("Entity not found")
}
Aval, _ = strconv.Atoi(string(Avalbytes))
Bvalbytes, err := stub.GetState(B)
if err != nil {
return shim.Error("Failed to get state")
}
if Bvalbytes == nil {
return shim.Error("Entity not found")
}
Bval, _ = strconv.Atoi(string(Bvalbytes))
// Perform the execution
X, err = strconv.Atoi(args[2])
if err != nil {
return shim.Error("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 shim.Error(err.Error())
}
err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
// Deletes an entity from state
func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
A := args[0]
// Delete the key from the state in ledger
err := stub.DelState(A)
if err != nil {
return shim.Error("Failed to delete state")
}
return shim.Success(nil)
}
// query callback representing the query of a chaincode
func (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response {
fmt.Println("Inside query method")
var A string // Entities
var err error
fmt.Println("\value of args in query method is: ", strings.Join(args, ", "))
if len(args) != 1 {
return shim.Error("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 shim.Error(jsonResp)
}
if Avalbytes == nil {
jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
return shim.Error(jsonResp)
}
jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
fmt.Printf("Query Response:%s\n", jsonResp)
return shim.Success(Avalbytes)
}
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
EDIT
After the run time error, I logged in to peer0.seller.mytrade.com cli using the command
docker exec -it cli bash and ran the peer chaincode query -C mychannel -n myproject -c '{"Args":["query","Seller"]}' command to query the chaincode and I got the result Seller = 100.
Before running the peer chaincode query command, the dev-peer0.seller.mytrade.com container was missing. Only container dev-peer1.seller.mytrade.com exist. But after the peer chaincode query command on peer0.seller.mytrade.com cli resulted in the chaincode container. Since the chaincode invoked on both the peers of Seller then both the containers should be there.
I also added 20s delay because I thought that docker is taking some time to create the container. But it didn't work.
PFA the image of docker ps -a command

Reading from reader until a string is reached

I am trying to write a function to keep reading from a buffered reader until I hit a certain string, then to stop reading and return everything read prior to that string.
In other words, I want to do the same thing as reader.ReadString() does, except taking a string instead of a single byte.
For instance:
mydata, err := reader.ReadString("\r\n.\r\n") //obviously will not compile
How can I do this?
Thanks in advance,
Twichy
Amendment 1: Previous attempt
Here is my previous attempt; its badly written and doesnt work but hopefully it demonstrates what I am trying to do.
func readDotData(reader *bufio.Reader)(string, error){
delims := []byte{ '\r', '\n', '.', '\r', '\n'}
curpos := 0
var buffer []byte
for {
curpos = 0
data, err := reader.ReadSlice(delims[0])
if err!=nil{ return "", err }
buffer = append(buffer, data...)
for {
curpos++
b, err := reader.ReadByte()
if err!=nil{ return "", err }
if b!=delims[curpos]{
for curpos >= 0{
buffer = append(buffer, delims[curpos])
curpos--
}
break
}
if curpos == len(delims){
return string(buffer[len(buffer)-1:]), nil
}
}
}
panic("unreachable")
}
package main
import (
"bytes"
"fmt"
"log"
)
type reader interface {
ReadString(delim byte) (line string, err error)
}
func read(r reader, delim []byte) (line []byte, err error) {
for {
s := ""
s, err = r.ReadString(delim[len(delim)-1])
if err != nil {
return
}
line = append(line, []byte(s)...)
if bytes.HasSuffix(line, delim) {
return line[:len(line)-len(delim)], nil
}
}
}
func main() {
src := bytes.NewBufferString("123deli456elim789delimABCdelimDEF")
for {
b, err := read(src, []byte("delim"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("%q\n", b)
}
}
Playground
Output:
"123deli456elim789"
"ABC"
2009/11/10 23:00:00 EOF
http://play.golang.org/p/BpA5pOc-Rn
package main
import (
"bytes"
"fmt"
)
func main() {
b := bytes.NewBuffer([]byte("Hello, playground!\r\n.\r\nIrrelevant trailer."))
c := make([]byte, 0, b.Len())
for {
p := b.Bytes()
if bytes.Equal(p[:5], []byte("\r\n.\r\n")) {
fmt.Println(string(c))
return
}
c = append(c, b.Next(1)...)
}
}
For example,
package main
import (
"bufio"
"bytes"
"fmt"
"strings"
)
var delim = []byte{'\r', '\n', '.', '\r', '\n'}
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
for i := 0; i+len(delim) <= len(data); {
j := i + bytes.IndexByte(data[i:], delim[0])
if j < i {
break
}
if bytes.Equal(data[j+1:j+len(delim)], delim[1:]) {
// We have a full delim-terminated line.
return j + len(delim), data[0:j], nil
}
i = j + 1
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func main() {
delims := string(delim)
input := "1234" + delims + "5678" + delims + "1234567901234567890" + delims
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(ScanLines)
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Printf("Invalid input: %s", err)
}
}
Output:
1234
5678
1234567901234567890
Because you have the same byte in the string, you can do it as below:
func readWithEnd(reader *bufio.Reader) ([]byte, error) {
message, err := reader.ReadBytes('#')
if err != nil {
return nil, err
}
a1, err := reader.ReadByte()
if err != nil {
return nil, err
}
message = append(message, a1)
if a1 != '\t' {
message2, err := readWithEnd(reader)
if err != nil {
return nil, err
}
ret := append(message, message2...)
return ret, nil
}
a2, err := reader.ReadByte()
if err != nil {
return nil, err
}
message = append(message, a2)
if a2 != '#' {
message2, err := readWithEnd(reader)
if err != nil {
return nil, err
}
ret := append(message, message2...)
return ret, nil
}
return message, nil
}
This is the sample that can recognize the "#\t#" in TCP connection

Resources