github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/orderer/sbft/simplebft/crypto.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 simplebft 18 19 import ( 20 "crypto/sha256" 21 "encoding/base64" 22 23 "github.com/golang/protobuf/proto" 24 ) 25 26 func hash2str(h []byte) string { 27 return base64.RawStdEncoding.EncodeToString(h) 28 } 29 30 func hash(data []byte) []byte { 31 h := sha256.Sum256(data) 32 return h[:] 33 } 34 35 func merkleHashData(data [][]byte) []byte { 36 var digests [][]byte 37 for _, d := range data { 38 digests = append(digests, hash(d)) 39 } 40 return merkleHashDigests(digests) 41 } 42 43 func merkleHashDigests(digests [][]byte) []byte { 44 for len(digests) > 1 { 45 var nextDigests [][]byte 46 var prev []byte 47 for _, d := range digests { 48 if prev == nil { 49 prev = d 50 } else { 51 h := sha256.New() 52 h.Write(prev) 53 h.Write(d) 54 nextDigests = append(nextDigests, h.Sum(nil)) 55 prev = nil 56 } 57 } 58 if prev != nil { 59 nextDigests = append(nextDigests, prev) 60 } 61 digests = nextDigests 62 } 63 64 if len(digests) == 0 { 65 return nil 66 } 67 return digests[0] 68 } 69 70 //////////////////////////////////////////////// 71 72 func (s *SBFT) sign(msg proto.Message) *Signed { 73 bytes, err := proto.Marshal(msg) 74 if err != nil { 75 panic(err) 76 } 77 sig := s.sys.Sign(bytes) 78 return &Signed{Data: bytes, Signature: []byte(sig)} 79 } 80 81 func (s *SBFT) checkSig(sig *Signed, signer uint64, msg proto.Message) error { 82 err := s.checkBytesSig(sig.Data, signer, sig.Signature) 83 if err != nil { 84 return err 85 } 86 err = proto.Unmarshal(sig.Data, msg) 87 if err != nil { 88 return err 89 } 90 return nil 91 } 92 93 func (s *SBFT) checkBytesSig(digest []byte, signer uint64, sig []byte) error { 94 return s.sys.CheckSig(digest, signer, sig) 95 }