github.com/true-sqn/fabric@v2.1.1+incompatible/core/ledger/kvledger/txmgmt/version/version.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 version 18 19 import ( 20 "fmt" 21 22 "github.com/hyperledger/fabric/common/ledger/util" 23 ) 24 25 // Height represents the height of a transaction in blockchain 26 type Height struct { 27 BlockNum uint64 28 TxNum uint64 29 } 30 31 // NewHeight constructs a new instance of Height 32 func NewHeight(blockNum, txNum uint64) *Height { 33 return &Height{blockNum, txNum} 34 } 35 36 // NewHeightFromBytes constructs a new instance of Height from serialized bytes 37 func NewHeightFromBytes(b []byte) (*Height, int, error) { 38 blockNum, n1, err := util.DecodeOrderPreservingVarUint64(b) 39 if err != nil { 40 return nil, -1, err 41 } 42 txNum, n2, err := util.DecodeOrderPreservingVarUint64(b[n1:]) 43 if err != nil { 44 return nil, -1, err 45 } 46 return NewHeight(blockNum, txNum), n1 + n2, nil 47 } 48 49 // ToBytes serializes the Height 50 func (h *Height) ToBytes() []byte { 51 blockNumBytes := util.EncodeOrderPreservingVarUint64(h.BlockNum) 52 txNumBytes := util.EncodeOrderPreservingVarUint64(h.TxNum) 53 return append(blockNumBytes, txNumBytes...) 54 } 55 56 // Compare return a -1, zero, or +1 based on whether this height is 57 // less than, equals to, or greater than the specified height respectively. 58 func (h *Height) Compare(h1 *Height) int { 59 res := 0 60 switch { 61 case h.BlockNum != h1.BlockNum: 62 res = int(h.BlockNum - h1.BlockNum) 63 break 64 case h.TxNum != h1.TxNum: 65 res = int(h.TxNum - h1.TxNum) 66 break 67 default: 68 return 0 69 } 70 if res > 0 { 71 return 1 72 } 73 return -1 74 } 75 76 // String returns string for printing 77 func (h *Height) String() string { 78 return fmt.Sprintf("{BlockNum: %d, TxNum: %d}", h.BlockNum, h.TxNum) 79 } 80 81 // AreSame returns true if both the heights are either nil or equal 82 func AreSame(h1 *Height, h2 *Height) bool { 83 if h1 == nil { 84 return h2 == nil 85 } 86 if h2 == nil { 87 return false 88 } 89 return h1.Compare(h2) == 0 90 }