From 04e9060484d28c96d5937569869ab471b9e6f342 Mon Sep 17 00:00:00 2001 From: anthdm Date: Thu, 1 Feb 2018 10:25:34 +0100 Subject: [PATCH] Added GetBlocks payload --- pkg/network/payload/getblocks.go | 48 +++++++++++++++++++++++++++ pkg/network/payload/getblocks_test.go | 37 +++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 pkg/network/payload/getblocks.go create mode 100644 pkg/network/payload/getblocks_test.go diff --git a/pkg/network/payload/getblocks.go b/pkg/network/payload/getblocks.go new file mode 100644 index 000000000..909335b9a --- /dev/null +++ b/pkg/network/payload/getblocks.go @@ -0,0 +1,48 @@ +package payload + +import ( + "encoding/binary" + "io" + + . "github.com/anthdm/neo-go/pkg/util" +) + +// GetBlocks payload +type GetBlocks struct { + // hash of latest block that node requests + HashStart []Uint256 + // hash of last block that node requests + HashStop Uint256 +} + +// NewGetBlocks return a pointer to a GetBlocks object. +func NewGetBlocks(start []Uint256, stop Uint256) *GetBlocks { + return &GetBlocks{ + HashStart: start, + HashStop: stop, + } +} + +// DecodeBinary implements the payload interface. +func (p *GetBlocks) DecodeBinary(r io.Reader) error { + var lenStart uint8 + + err := binary.Read(r, binary.LittleEndian, &lenStart) + p.HashStart = make([]Uint256, lenStart) + err = binary.Read(r, binary.LittleEndian, &p.HashStart) + err = binary.Read(r, binary.LittleEndian, &p.HashStop) + + return err +} + +// EncodeBinary implements the payload interface. +func (p *GetBlocks) EncodeBinary(w io.Writer) error { + err := binary.Write(w, binary.LittleEndian, uint8(len(p.HashStart))) + err = binary.Write(w, binary.LittleEndian, p.HashStart) + err = binary.Write(w, binary.LittleEndian, p.HashStop) + + return err +} + +// Size implements the payload interface. +func (p *GetBlocks) Size() uint32 { return 0 } diff --git a/pkg/network/payload/getblocks_test.go b/pkg/network/payload/getblocks_test.go new file mode 100644 index 000000000..c73772386 --- /dev/null +++ b/pkg/network/payload/getblocks_test.go @@ -0,0 +1,37 @@ +package payload + +import ( + "bytes" + "crypto/sha256" + "reflect" + "testing" + + . "github.com/anthdm/neo-go/pkg/util" +) + +func TestGetBlocksEncodeDecode(t *testing.T) { + start := []Uint256{ + sha256.Sum256([]byte("a")), + sha256.Sum256([]byte("b")), + } + stop := sha256.Sum256([]byte("c")) + + p := NewGetBlocks(start, stop) + buf := new(bytes.Buffer) + if err := p.EncodeBinary(buf); err != nil { + t.Fatal(err) + } + + if have, want := buf.Len(), 1+64+32; have != want { + t.Fatalf("expecting a length of %d got %d", want, have) + } + + pDecode := &GetBlocks{} + if err := pDecode.DecodeBinary(buf); err != nil { + t.Fatal(err) + } + + if !reflect.DeepEqual(p, pDecode) { + t.Fatalf("expecting both getblocks payloads to be equal %v and %v", p, pDecode) + } +}