github.com/iotexproject/iotex-core@v1.14.1-rc1/blockchain/block/footer.go (about) 1 // Copyright (c) 2019 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package block 7 8 import ( 9 "time" 10 11 "google.golang.org/protobuf/proto" 12 "google.golang.org/protobuf/types/known/timestamppb" 13 14 "github.com/iotexproject/iotex-core/endorsement" 15 "github.com/iotexproject/iotex-proto/golang/iotextypes" 16 ) 17 18 // Footer defines a set of proof of this block 19 type Footer struct { 20 endorsements []*endorsement.Endorsement 21 commitTime time.Time 22 } 23 24 // ConvertToBlockFooterPb converts BlockFooter 25 func (f *Footer) ConvertToBlockFooterPb() (*iotextypes.BlockFooter, error) { 26 pb := iotextypes.BlockFooter{} 27 commitTime := timestamppb.New(f.commitTime) 28 pb.Timestamp = commitTime 29 pb.Endorsements = []*iotextypes.Endorsement{} 30 for _, en := range f.endorsements { 31 ePb, err := en.Proto() 32 if err != nil { 33 return nil, err 34 } 35 pb.Endorsements = append(pb.Endorsements, ePb) 36 } 37 return &pb, nil 38 } 39 40 // ConvertFromBlockFooterPb converts BlockFooter to BlockFooter 41 func (f *Footer) ConvertFromBlockFooterPb(pb *iotextypes.BlockFooter) error { 42 if pb == nil { 43 return nil 44 } 45 if err := pb.GetTimestamp().CheckValid(); err != nil { 46 return err 47 } 48 commitTime := pb.GetTimestamp().AsTime() 49 f.commitTime = commitTime 50 pbEndorsements := pb.GetEndorsements() 51 if pbEndorsements == nil { 52 return nil 53 } 54 f.endorsements = []*endorsement.Endorsement{} 55 for _, ePb := range pbEndorsements { 56 e := &endorsement.Endorsement{} 57 if err := e.LoadProto(ePb); err != nil { 58 return err 59 } 60 f.endorsements = append(f.endorsements, e) 61 } 62 63 return nil 64 } 65 66 // CommitTime returns the timestamp the block was committed 67 func (f *Footer) CommitTime() time.Time { 68 return f.commitTime 69 } 70 71 // Endorsements returns the number of commit endorsements froms delegates 72 func (f *Footer) Endorsements() []*endorsement.Endorsement { 73 return f.endorsements 74 } 75 76 // Serialize returns the serialized byte stream of the block footer 77 func (f *Footer) Serialize() ([]byte, error) { 78 pb, err := f.ConvertToBlockFooterPb() 79 if err != nil { 80 return nil, err 81 } 82 return proto.Marshal(pb) 83 } 84 85 // Deserialize loads from the serialized byte stream 86 func (f *Footer) Deserialize(buf []byte) error { 87 pb := &iotextypes.BlockFooter{} 88 if err := proto.Unmarshal(buf, pb); err != nil { 89 return err 90 } 91 return f.ConvertFromBlockFooterPb(pb) 92 }