From 3ea5c1a3220bd3f647606982535ac45e287f8b1f Mon Sep 17 00:00:00 2001 From: Jan Barfuss Date: Sun, 12 Jan 2025 02:03:55 +0100 Subject: [PATCH] Added an CRC Checksum, v0.2.0 --- go.mod | 2 ++ go.sum | 2 ++ spf.go | 20 ++++++++++++++++++-- spf_test.go | 4 ++-- 4 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 go.sum diff --git a/go.mod b/go.mod index 42c9046..4514184 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.barfuss.email/jan/SimpleFinancePackage go 1.22.1 + +require git.barfuss.email/jan/crc16 v0.1.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e786f4c --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +git.barfuss.email/jan/crc16 v0.1.0 h1:9u/m/JO1/njaR6w2WsGTVezW/niYlT1tBRK2mRDR92w= +git.barfuss.email/jan/crc16 v0.1.0/go.mod h1:ibTarWCN7/nak76mWoU/pNhF+O0VzKX+8YpDftjc8LU= diff --git a/spf.go b/spf.go index 107c02b..f9a78f8 100644 --- a/spf.go +++ b/spf.go @@ -5,6 +5,8 @@ import ( "encoding/binary" "errors" "fmt" + + crc "git.barfuss.email/jan/crc16" ) type SimpleFinancePackage struct { @@ -13,11 +15,18 @@ type SimpleFinancePackage struct { Asset byte // 1 byte for asset Price float64 // 8 bytes for price (float64 for precision) Volume float64 // 8 bytes for volume + CRC uint16 // 2 bytes for CRC } func ParseSimpleFinanacePackage(data []byte) (*SimpleFinancePackage, error) { - if len(data) != 26 { - return nil, errors.New("invalid packet size, expected 26 bytes") + if len(data) != 28 { + return nil, errors.New("invalid packet size, expected 28 bytes") + } + + //Check CRC + check := binary.BigEndian.Uint16(data[26:]) + if check != crc.Calculate(data[:26]) { + return nil, errors.New("CRC check failed") } reader := bytes.NewReader(data) @@ -59,6 +68,13 @@ func EncodeSimpleFinanacePackage(packet SimpleFinancePackage) ([]byte, error) { return nil, fmt.Errorf("failed to encode volume: %w", err) } + // Calculate and write CRC + packet.CRC = crc.Calculate(buf.Bytes()) + + if err := binary.Write(buf, binary.BigEndian, packet.CRC); err != nil { + return nil, fmt.Errorf("failed to encode CRC: %w", err) + } + // Return the resulting byte slice return buf.Bytes(), nil } diff --git a/spf_test.go b/spf_test.go index c09b9c8..1ee4512 100644 --- a/spf_test.go +++ b/spf_test.go @@ -24,8 +24,8 @@ func TestEncodeDecodeCustomPacket(t *testing.T) { } // Check the encoded length - if len(encoded) != 26 { - t.Fatalf("Encoded data has incorrect length: got %d, want 26", len(encoded)) + if len(encoded) != 28 { + t.Fatalf("Encoded data has incorrect length: got %d, want 28", len(encoded)) } // Decode the packet