github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/examples/chaincode/go/utxo/store.go (about) 1 /* 2 Copyright IBM Corp. 2016 All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "fmt" 21 22 "github.com/golang/protobuf/proto" 23 "github.com/hyperledger/fabric/core/chaincode/shim" 24 "github.com/hyperledger/fabric/examples/chaincode/go/utxo/util" 25 ) 26 27 // Store struct uses a chaincode stub for state access 28 type Store struct { 29 stub shim.ChaincodeStubInterface 30 } 31 32 // MakeChaincodeStore returns a store for storing keys in the state 33 func MakeChaincodeStore(stub shim.ChaincodeStubInterface) util.Store { 34 store := &Store{} 35 store.stub = stub 36 return store 37 } 38 39 func keyToString(key *util.Key) string { 40 return key.TxHashAsHex + ":" + string(key.TxIndex) 41 } 42 43 // GetState returns the transaction for a given key 44 func (s *Store) GetState(key util.Key) (*util.TX_TXOUT, bool, error) { 45 keyToFetch := keyToString(&key) 46 data, err := s.stub.GetState(keyToFetch) 47 if err != nil { 48 return nil, false, fmt.Errorf("Error getting state from stub: %s", err) 49 } 50 if data == nil { 51 return nil, false, nil 52 } 53 // Value found, unmarshal 54 var value = &util.TX_TXOUT{} 55 err = proto.Unmarshal(data, value) 56 if err != nil { 57 return nil, false, fmt.Errorf("Error unmarshalling value: %s", err) 58 } 59 return value, true, nil 60 } 61 62 // DelState deletes the transaction for the given key 63 func (s *Store) DelState(key util.Key) error { 64 return s.stub.DelState(keyToString(&key)) 65 } 66 67 // PutState stores the given transaction and key 68 func (s *Store) PutState(key util.Key, value *util.TX_TXOUT) error { 69 data, err := proto.Marshal(value) 70 if err != nil { 71 return fmt.Errorf("Error marshalling value to bytes: %s", err) 72 } 73 return s.stub.PutState(keyToString(&key), data) 74 } 75 76 // GetTran returns a transaction for the given hash 77 func (s *Store) GetTran(key string) ([]byte, bool, error) { 78 data, err := s.stub.GetState(key) 79 if err != nil { 80 return nil, false, fmt.Errorf("Error getting state from stub: %s", err) 81 } 82 if data == nil { 83 return nil, false, nil 84 } 85 return data, true, nil 86 } 87 88 // PutTran adds a transaction to the state with the hash as a key 89 func (s *Store) PutTran(key string, value []byte) error { 90 return s.stub.PutState(key, value) 91 }