Skip to content

Instantly share code, notes, and snippets.

@tboloo
Created June 7, 2018 09:49
Show Gist options
  • Save tboloo/4195609c5786e4c4f82553d2b108bb61 to your computer and use it in GitHub Desktop.
Save tboloo/4195609c5786e4c4f82553d2b108bb61 to your computer and use it in GitHub Desktop.
records user name to the ledger
package main
import (
"github.com/op/go-logging"
"os"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/hyperledger/fabric/core/chaincode/lib/cid"
)
var logger = logging.MustGetLogger("acl")
var format = logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.8s} %{id:03x}%{color:reset} %{message}`,
)
var user_name string
type SimpleChaincode struct {
}
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
logger.Debug("Initializing SimpleChaincode")
resp := "Initialized"
logger.Debug(resp)
return shim.Success([]byte(resp))
}
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
logger.Debug("Invoking Chaincode...")
function, args := stub.GetFunctionAndParameters()
if function == "write_to_ledger" {
return t.write_to_ledger(stub, args)
}
return shim.Error("Invalid invoke function name. Expecting \"write_to_ledger\" or \"get_attribute\".")
}
func (t* SimpleChaincode) write_to_ledger(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger.Debug("Invoking write_to_ledger")
var user_name string
val, ok, err := cid.GetAttributeValue(stub, "hf.EnrollmentID")
if err != nil {
return shim.Error(err.Error())
}
if ok {
user_name = val
}
err = stub.PutState(user_name, []byte(user_name + " can write to ledger"))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(user_name + " wrote to ledger"))
}
func main() {
backend1 := logging.NewLogBackend(os.Stderr, "", 0)
backend2 := logging.NewLogBackend(os.Stderr, "", 0)
// For messages written to backend2 we want to add some additional
// information to the output, including the used log level and the name of
// the function.
backend2Formatter := logging.NewBackendFormatter(backend2, format)
// Only errors and more severe messages should be sent to backend1
backend1Leveled := logging.AddModuleLevel(backend1)
backend1Leveled.SetLevel(logging.ERROR, "")
logging.SetBackend(backend1Leveled, backend2Formatter)
logger.Debug("Starting SimpleChaincode")
err := shim.Start(new(SimpleChaincode))
if err != nil {
logger.Errorf("Error starting Simple chaincode: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment