forked from s7techlab/cckit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mockstub.go
274 lines (225 loc) · 7.69 KB
/
mockstub.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package testing
import (
"fmt"
"math/rand"
"time"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/msp"
"github.com/hyperledger/fabric/protos/peer"
"github.com/pkg/errors"
"github.com/s7techlab/cckit/convert"
)
const EventChannelBufferSize = 100
var (
// ErrChaincodeNotExists occurs when attempting to invoke a nonexostent external chaincode
ErrChaincodeNotExists = errors.New(`chaincode not exists`)
// ErrUnknownFromArgsType occurs when attempting to set unknown args in From func
ErrUnknownFromArgsType = errors.New(`unknown args type to cckit.MockStub.From func`)
)
// MockStub replacement of shim.MockStub with creator mocking facilities
type MockStub struct {
shim.MockStub
cc shim.Chaincode
mockCreator []byte
transient map[string][]byte
ClearCreatorAfterInvoke bool
_args [][]byte
InvokablesFull map[string]*MockStub // invokable this version of MockStub
creatorTransformer CreatorTransformer // transformer for tx creator data, used in From func
ChaincodeEvent *peer.ChaincodeEvent // event in last tx
chaincodeEventSubscriptions []chan *peer.ChaincodeEvent // multiple event subscriptions
}
type CreatorTransformer func(...interface{}) (mspID string, certPEM []byte, err error)
// NewMockStub creates MockStub
func NewMockStub(name string, cc shim.Chaincode) *MockStub {
return &MockStub{
MockStub: *shim.NewMockStub(name, cc),
cc: cc,
ClearCreatorAfterInvoke: true, // by default clear tx creator data after each cc method invoke
InvokablesFull: make(map[string]*MockStub),
}
}
// GetArgs mocked args
func (stub *MockStub) GetArgs() [][]byte {
return stub._args
}
// SetArgs set mocked args
func (stub *MockStub) SetArgs(args [][]byte) {
stub._args = args
}
// SetEvent sets chaincode event
func (stub *MockStub) SetEvent(name string, payload []byte) error {
if name == "" {
return errors.New("event name can not be nil string")
}
stub.ChaincodeEvent = &peer.ChaincodeEvent{EventName: name, Payload: payload}
for _, sub := range stub.chaincodeEventSubscriptions {
sub <- stub.ChaincodeEvent
}
return stub.MockStub.SetEvent(name, payload)
}
func (stub *MockStub) EventSubscription() chan *peer.ChaincodeEvent {
subscription := make(chan *peer.ChaincodeEvent, EventChannelBufferSize)
stub.chaincodeEventSubscriptions = append(stub.chaincodeEventSubscriptions, subscription)
return subscription
}
// ClearEvents clears chaincode events channel -
func (stub *MockStub) ClearEvents() {
for len(stub.ChaincodeEventsChannel) > 0 {
<-stub.ChaincodeEventsChannel
}
}
// GetStringArgs get mocked args as strings
func (stub *MockStub) GetStringArgs() []string {
args := stub.GetArgs()
strargs := make([]string, 0, len(args))
for _, barg := range args {
strargs = append(strargs, string(barg))
}
return strargs
}
// MockPeerChaincode link to another MockStub
func (stub *MockStub) MockPeerChaincode(invokableChaincodeName string, otherStub *MockStub) {
stub.InvokablesFull[invokableChaincodeName] = otherStub
}
// MockedPeerChancodes returns names of mocked chaincodes, available for invoke from current stub
func (stub *MockStub) MockedPeerChancodes() []string {
keys := make([]string, 0)
for k := range stub.InvokablesFull {
keys = append(keys, k)
}
return keys
}
// InvokeChaincode using another MockStub
func (stub *MockStub) InvokeChaincode(chaincodeName string, args [][]byte, channel string) peer.Response {
// TODO "args" here should possibly be a serialized pb.ChaincodeInput
// Internally we use chaincode name as a composite name
ccName := chaincodeName
if channel != "" {
chaincodeName = chaincodeName + "/" + channel
}
otherStub, exists := stub.InvokablesFull[chaincodeName]
if !exists {
return shim.Error(fmt.Sprintf(`%s: try to invoke chaincode "%s" in channel "%s" (%s). Available mocked chaincodes are: %s`,
ErrChaincodeNotExists, ccName, channel, chaincodeName, stub.MockedPeerChancodes()))
}
res := otherStub.MockInvoke(stub.TxID, args)
return res
}
// GetFunctionAndParameters mocked
func (stub *MockStub) GetFunctionAndParameters() (function string, params []string) {
allargs := stub.GetStringArgs()
function = ""
params = []string{}
if len(allargs) >= 1 {
function = allargs[0]
params = allargs[1:]
}
return
}
// RegisterCreatorTransformer that transforms creator data to MSP_ID and X.509 certificate
func (stub *MockStub) RegisterCreatorTransformer(creatorTransformer CreatorTransformer) *MockStub {
stub.creatorTransformer = creatorTransformer
return stub
}
// MockCreator of tx
func (stub *MockStub) MockCreator(mspID string, certPEM []byte) {
stub.mockCreator, _ = msp.NewSerializedIdentity(mspID, certPEM)
}
func (stub *MockStub) generateTxUID() string {
id := make([]byte, 32)
rand.Seed(time.Now().UnixNano())
rand.Read(id)
return fmt.Sprintf("0x%x", id)
}
// Init func of chaincode - sugared version with autogenerated tx uuid
func (stub *MockStub) Init(iargs ...interface{}) peer.Response {
args, err := convert.ArgsToBytes(iargs...)
if err != nil {
return shim.Error(err.Error())
}
return stub.MockInit(stub.generateTxUID(), args)
}
// MockInit mocked init function
func (stub *MockStub) MockInit(uuid string, args [][]byte) peer.Response {
stub.SetArgs(args)
stub.MockTransactionStart(uuid)
res := stub.cc.Init(stub)
stub.MockTransactionEnd(uuid)
if stub.ClearCreatorAfterInvoke {
stub.mockCreator = nil
stub.transient = nil
}
return res
}
// MockQuery
func (stub *MockStub) MockQuery(uuid string, args [][]byte) peer.Response {
return stub.MockInvoke(uuid, args)
}
// MockInvoke
func (stub *MockStub) MockInvoke(uuid string, args [][]byte) peer.Response {
// this is a hack here to set MockStub.args, because its not accessible otherwise
stub.SetArgs(args)
//empty event
stub.ChaincodeEvent = nil
// now do the invoke with the correct stub
stub.MockTransactionStart(uuid)
res := stub.cc.Invoke(stub)
stub.MockTransactionEnd(uuid)
if stub.ClearCreatorAfterInvoke {
stub.mockCreator = nil
stub.transient = nil
}
return res
}
// Invoke sugared invoke function with autogenerated tx uuid
func (stub *MockStub) Invoke(funcName string, iargs ...interface{}) peer.Response {
fargs, err := convert.ArgsToBytes(iargs...)
if err != nil {
return shim.Error(err.Error())
}
args := append([][]byte{[]byte(funcName)}, fargs...)
return stub.InvokeBytes(args...)
}
// InvokeByte mock invoke with autogenerated tx uuid
func (stub *MockStub) InvokeBytes(args ...[]byte) peer.Response {
return stub.MockInvoke(stub.generateTxUID(), args)
}
func (stub *MockStub) QueryBytes(args ...[]byte) peer.Response {
return stub.MockQuery(stub.generateTxUID(), args)
}
func (stub *MockStub) Query(funcName string, iargs ...interface{}) peer.Response {
return stub.Invoke(funcName, iargs...)
}
// GetCreator mocked
func (stub *MockStub) GetCreator() ([]byte, error) {
return stub.mockCreator, nil
}
// From mock tx creator
func (stub *MockStub) From(txCreator ...interface{}) *MockStub {
var mspID string
var certPEM []byte
var err error
if stub.creatorTransformer != nil {
mspID, certPEM, err = stub.creatorTransformer(txCreator...)
} else {
mspID, certPEM, err = TransformCreator(txCreator...)
}
if err != nil {
panic(err)
}
stub.MockCreator(mspID, certPEM)
return stub
}
func (stub *MockStub) GetTransient() (map[string][]byte, error) {
return stub.transient, nil
}
func (stub *MockStub) WithTransient(transient map[string][]byte) *MockStub {
stub.transient = transient
return stub
}
// At mock tx timestamp
//func (stub *MockStub) At(txTimestamp *timestamp.Timestamp) *MockStub {
// stub.TxTimestamp = txTimestamp
// return stub
//}