chaincode/monnethic_environment_&_strcture_build.go
2019-04-06 19:23:19 +02:00

204 lines
6.8 KiB
Go

/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
//WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of
//calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has
//to be modified as well with the new ID of chaincode_example02.
//chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of
//hard-coding.
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}
type owner struct {
ObjectType string `json:"docType"`
UserId string `json:"userId"`
UserName string `json:"userName"`
UserFirstName string `json:"userFirstName"`
UserPhone string `json:"userPhone"`
UserAssociation string `json:"userAssociation"`
UserAuthorized bool `json:"userAuthorized"`
}
type wallet struct {
ObjectType string `json:"docType"` //docType is used to distinguish the various type$
Id string `json:"id"` //the fieldtags are needed to keep case from bounci$
WalletType string `json:"walletType"`
Balance float64 `json:"balance"`
Owner string `json:"owner"`
}
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("monnethic Init")
return shim.Success(nil)
}
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)
} else if function == "register" {
// register a new user into the ledger
return t.register(stub, args)
} else if function == "registerUser" {
// initiate a new account
return t.registerUser(stub, args)
} else if function == "readUser" {
// query a specific user from the ledger
return t.readUser(stub, args)
} else if function == "deleteUser" {
// delete a specific user from the ledger
return t.deleteUser(stub, args)
} else if function == "setUserPermission" {
// change the permission of an account
return t.setUserPermission(stub, args)
} else if function == "initWallet" {
// initiate a new wallet
return t.initWallet(stub, args)
} else if function == "readWallet" {
// query a specific wallet from the ledger
return t.readWallet(stub, args)
} else if function == "deleteWallet" {
// delete a specific wallet from the ledger
return t.deleteWallet(stub, args)
} else if function == "transferWallet" {
// change the owner of a specific wallet
return t.transferWallet(stub, args)
} else if function == "setBalanceOnWallet" {
// set a new balance to a wallet
return t.setBalanceOnWallet(stub, args)
} else if function == "transaction" {
// make a transaction of X units from a wallet to an other
return t.transaction(stub, args)
} else if function == "queryWalletsByOwner" {
// get all wallets of a user by querying his specific account
return t.queryWalletsByOwner(stub, args)
} else if function == "queryWalletsByType" {
// get all wallets of a specific wallet type by querying a specific type
return t.queryWalletsByType(stub, args)
} else if function == "queryWallets" {
// get a specific wallet
return t.queryWallets(stub, args)
} else if function == "getHistoryForWallet" {
// query the full state history of a wallet
return t.getHistoryForWallet(stub, args)
} else if function == "getAllEntities" {
// get All Entities of the present ledger
return t.getAllEntities(stub, args)
}
return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\" \"register\"")
}
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
// ===========================================================================================
// constructQueryResponseFromIterator constructs a JSON array containing query results from
// a given result iterator
// ===========================================================================================
func constructQueryResponseFromIterator(resultsIterator shim.StateQueryIteratorInterface) (*bytes.Buffer, error) {
// buffer is a JSON array containing QueryResults
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"Key\":")
buffer.WriteString("\"")
buffer.WriteString(queryResponse.Key)
buffer.WriteString("\"")
buffer.WriteString(", \"Record\":")
// Record is a JSON object, so we write as-is
buffer.WriteString(string(queryResponse.Value))
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
return &buffer, nil
}
// =========================================================================================
// getQueryResultForQueryString executes the passed in query string.
// Result set is built and returned as a byte array containing the JSON results.
// =========================================================================================
func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {
fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString)
resultsIterator, err := stub.GetQueryResult(queryString)
if err != nil {
return nil, err
}
defer resultsIterator.Close()
buffer, err := constructQueryResponseFromIterator(resultsIterator)
if err != nil {
return nil, err
}
fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
return buffer.Bytes(), nil
}