From 9f97fd4fa631e8cfd3f3313ed6dca780e6435a36 Mon Sep 17 00:00:00 2001 From: Daniel Vladco Date: Mon, 19 Aug 2024 13:37:54 +0300 Subject: [PATCH] feat: add scale codec tests to header (#28) * feat: add codec tests --- internal/block/header_test.go | 86 +++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 internal/block/header_test.go diff --git a/internal/block/header_test.go b/internal/block/header_test.go new file mode 100644 index 0000000..bb7bc67 --- /dev/null +++ b/internal/block/header_test.go @@ -0,0 +1,86 @@ +package block + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/eigerco/strawberry/internal/crypto" + "github.com/eigerco/strawberry/internal/jamtime" + "github.com/eigerco/strawberry/pkg/serialization" + "github.com/eigerco/strawberry/pkg/serialization/codec" +) + +func Test_HeaderEncodeDecode(t *testing.T) { + h := Header{ + ParentHash: randomHash(t), + PriorStateRoot: randomHash(t), + ExtrinsicHash: randomHash(t), + TimeSlotIndex: 123, + EpochMarker: &EpochMarker{ + Keys: [NumberOfValidators]crypto.BandersnatchPublicKey{ + randomPublicKey(t), + randomPublicKey(t), + }, + Entropy: randomHash(t), + }, + WinningTicketsMarker: [jamtime.TimeslotsPerEpoch]*Ticket{{ + Identifier: randomHash(t), + EntryIndex: 111, + }, { + Identifier: randomHash(t), + EntryIndex: 222, + }}, + Verdicts: []crypto.Hash{ + randomHash(t), + randomHash(t), + }, + OffendersMarkers: []crypto.Ed25519PublicKey{ + randomED25519PublicKey(t), + }, + BlockAuthorIndex: 1, + VRFSignature: randomSignature(t), + BlockSealSignature: randomSignature(t), + } + serializer := serialization.NewSerializer(&codec.SCALECodec{}) + bb, err := serializer.Encode(h) + if err != nil { + t.Fatal(err) + } + + h2 := Header{} + err = serializer.Decode(bb, &h2) + if err != nil { + t.Fatal(err) + } + + assert.Equal(t, h, h2) +} + +func randomHash(t *testing.T) crypto.Hash { + hash := make([]byte, crypto.HashSize) + _, err := rand.Read(hash) + require.NoError(t, err) + return crypto.Hash(hash) +} +func randomED25519PublicKey(t *testing.T) crypto.Ed25519PublicKey { + hash := make([]byte, ed25519.PublicKeySize) + _, err := rand.Read(hash) + require.NoError(t, err) + return hash +} +func randomPublicKey(t *testing.T) crypto.BandersnatchPublicKey { + hash := make([]byte, crypto.BandersnatchSize) + _, err := rand.Read(hash) + require.NoError(t, err) + return crypto.BandersnatchPublicKey(hash) +} +func randomSignature(t *testing.T) crypto.BandersnatchSignature { + hash := make([]byte, 96) + _, err := rand.Read(hash) + require.NoError(t, err) + return crypto.BandersnatchSignature(hash) +}