github.com/s7techlab/cckit@v0.10.5/extensions/encryption/testing/mockstub.go (about) 1 package testing 2 3 import ( 4 "crypto/rand" 5 "fmt" 6 7 "github.com/hyperledger/fabric-protos-go/peer" 8 9 "github.com/s7techlab/cckit/extensions/encryption" 10 "github.com/s7techlab/cckit/response" 11 testcc "github.com/s7techlab/cckit/testing" 12 ) 13 14 // MockStub wrapper for querying and invoking encrypted chaincode 15 type MockStub struct { 16 MockStub *testcc.MockStub 17 //EncKey key for encrypt data before query/invoke 18 EncKey []byte 19 20 // DecryptInvokeResponse decrypts invoker responses 21 DecryptInvokeResponse bool 22 } 23 24 func RandKey() []byte { 25 encKey := make([]byte, 32) 26 _, _ = rand.Read(encKey) 27 return encKey 28 } 29 30 // NewMockStub creates wrapper for querying and invoking encrypted chaincode 31 func NewMockStub(mockStub *testcc.MockStub, encKeys ...[]byte) *MockStub { 32 encKey := RandKey() 33 if len(encKeys) == 1 { 34 encKey = encKeys[0] 35 } 36 37 return &MockStub{ 38 MockStub: mockStub, 39 EncKey: encKey} 40 } 41 42 func (s *MockStub) Invoke(args ...interface{}) (response peer.Response) { 43 var ( 44 err error 45 decrypted []byte 46 ) 47 // first we encrypt all args 48 response = MockInvoke(s.MockStub, s.EncKey, args...) 49 50 //after receiving response we can decrypt received peer response 51 // actual only for invoke, query responses are not encrypted 52 if s.DecryptInvokeResponse && len(response.Payload) > 0 && string(response.Payload) != `null` { 53 if decrypted, err = encryption.Decrypt(s.EncKey, response.Payload); err != nil { 54 panic(fmt.Sprintf( 55 `decrypt mock invoke error with payload %s (%d): %s`, 56 string(response.Payload), len(response.Payload), err)) 57 } 58 response.Payload = decrypted 59 } 60 61 return response 62 } 63 64 func (s *MockStub) Query(args ...interface{}) peer.Response { 65 return MockQuery(s.MockStub, s.EncKey, args...) 66 } 67 68 func (s *MockStub) Init(args ...interface{}) peer.Response { 69 encArgs, err := encryption.EncryptArgs(s.EncKey, args...) 70 if err != nil { 71 return response.Error(`unable to encrypt input args`) 72 } 73 return s.MockStub.AddTransient(encryption.TransientMapWithKey(s.EncKey)).InitBytes(encArgs...) 74 } 75 76 func (s *MockStub) From(args ...interface{}) *MockStub { 77 s.MockStub.From(args...) 78 return s 79 } 80 81 func (s *MockStub) LastEvent() *peer.ChaincodeEvent { 82 return encryption.MustDecryptEvent(s.EncKey, s.MockStub.ChaincodeEvent) 83 }