forked from s7techlab/cckit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing.go
72 lines (59 loc) · 2.23 KB
/
testing.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
package encryption
import (
"fmt"
"github.com/hyperledger/fabric/protos/peer"
"github.com/s7techlab/cckit/response"
"github.com/s7techlab/cckit/testing"
)
// MockInvoke helper for invoking MockStub with transient key and encrypted args
func MockInvoke(cc *testing.MockStub, encKey []byte, args ...interface{}) peer.Response {
encArgs, err := EncryptArgs(encKey, args...)
if err != nil {
return response.Error(`unable to encrypt input args`)
}
return cc.WithTransient(TransientMapWithKey(encKey)).InvokeBytes(encArgs...)
}
// MockQuery helper for querying MockStub with transient key and encrypted args
func MockQuery(cc *testing.MockStub, encKey []byte, args ...interface{}) peer.Response {
encArgs, err := EncryptArgs(encKey, args...)
if err != nil {
return response.Error(`unable to encrypt input args`)
}
return cc.WithTransient(TransientMapWithKey(encKey)).QueryBytes(encArgs...)
}
// MockStub wrapper for querying and invoking encrypted chaincode
type MockStub struct {
MockStub *testing.MockStub
//EncKey key for encrypt data before query/invoke
EncKey []byte
// DecryptInvokeResponse decrypts invoker responses
DecryptInvokeResponse bool
}
// NewMockStub creates wrapper for querying and invoking encrypted chaincode
func NewMockStub(mockStub *testing.MockStub, encKey []byte) *MockStub {
return &MockStub{MockStub: mockStub, EncKey: encKey}
}
func (s *MockStub) Invoke(args ...interface{}) (response peer.Response) {
var (
err error
decrypted []byte
)
// first we encrypt all args
response = MockInvoke(s.MockStub, s.EncKey, args...)
//after receiving response we can decrypt received peer responce
// actual only for invoke, query responses are not encrypted
if s.DecryptInvokeResponse && len(response.Payload) > 0 && string(response.Payload) != `null` {
if decrypted, err = Decrypt(s.EncKey, response.Payload); err != nil {
panic(fmt.Sprintf(`decrypt mock invoke error with payload %s (%d): %s`, string(response.Payload), len(response.Payload), err))
}
response.Payload = decrypted
}
return response
}
func (s *MockStub) Query(args ...interface{}) peer.Response {
return MockQuery(s.MockStub, s.EncKey, args...)
}
func (s *MockStub) From(args ...interface{}) *MockStub {
s.MockStub.From(args...)
return s
}