github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/protos/common/block_test.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 common 18 19 import ( 20 "encoding/asn1" 21 "math" 22 "testing" 23 24 "github.com/hyperledger/fabric/common/util" 25 "github.com/stretchr/testify/assert" 26 ) 27 28 func TestBlock(t *testing.T) { 29 var block *Block 30 assert.Nil(t, block.GetHeader()) 31 assert.Nil(t, block.GetData()) 32 assert.Nil(t, block.GetMetadata()) 33 34 data := &BlockData{ 35 Data: [][]byte{[]byte{0, 1, 2}}, 36 } 37 block = NewBlock(uint64(0), []byte("datahash")) 38 assert.Equal(t, []byte("datahash"), block.Header.PreviousHash, "Incorrect previous hash") 39 assert.NotNil(t, block.GetData()) 40 assert.NotNil(t, block.GetMetadata()) 41 block.GetHeader().DataHash = data.Hash() 42 43 asn1Bytes, err := asn1.Marshal(asn1Header{ 44 Number: int64(uint64(0)), 45 DataHash: data.Hash(), 46 PreviousHash: []byte("datahash"), 47 }) 48 headerHash := util.ComputeSHA256(asn1Bytes) 49 assert.NoError(t, err) 50 assert.Equal(t, asn1Bytes, block.Header.Bytes(), "Incorrect marshaled blockheader bytes") 51 assert.Equal(t, headerHash, block.Header.Hash(), "Incorrect blockheader hash") 52 53 } 54 55 func TestGoodBlockHeaderBytes(t *testing.T) { 56 goodBlockHeader := &BlockHeader{ 57 Number: 1, 58 PreviousHash: []byte("foo"), 59 DataHash: []byte("bar"), 60 } 61 62 _ = goodBlockHeader.Bytes() // Should not panic 63 } 64 65 func TestBadBlockHeaderBytes(t *testing.T) { 66 defer func() { 67 if recover() == nil { 68 t.Fatalf("Should have panicked on block number too high to encode as int64") 69 } 70 }() 71 72 badBlockHeader := &BlockHeader{ 73 Number: math.MaxUint64, 74 PreviousHash: []byte("foo"), 75 DataHash: []byte("bar"), 76 } 77 78 _ = badBlockHeader.Bytes() // Should panic 79 }