-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
samplesyscc.go
91 lines (72 loc) · 2.41 KB
/
samplesyscc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
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 samplesyscc
import (
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
// SampleSysCC example simple Chaincode implementation
type SampleSysCC struct {
}
// Init initializes the sample system chaincode by storing the key and value
// arguments passed in as parameters
func (t *SampleSysCC) Init(stub shim.ChaincodeStubInterface) pb.Response {
//as system chaincodes do not take part in consensus and are part of the system,
//best practice to do nothing (or very little) in Init.
return shim.Success(nil)
}
// Invoke gets the supplied key and if it exists, updates the key with the newly
// supplied value.
func (t *SampleSysCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
f, args := stub.GetFunctionAndParameters()
switch f {
case "putval":
if len(args) != 2 {
return shim.Error("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 shim.Error(jsonResp)
}
// Write the state to the ledger
err = stub.PutState(key, []byte(val))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
case "getval":
var err error
if len(args) != 1 {
return shim.Error("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 shim.Error(jsonResp)
}
if valbytes == nil {
jsonResp := "{\"Error\":\"Nil val for " + key + "\"}"
return shim.Error(jsonResp)
}
return shim.Success(valbytes)
default:
jsonResp := "{\"Error\":\"Unknown function " + f + "\"}"
return shim.Error(jsonResp)
}
}