Add msgpack wire protocol with halfsiphash checksums
This commit is contained in:
40
lib/wire/wire.go
Normal file
40
lib/wire/wire.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package wire
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/theater/picomap/lib/halfsiphash"
|
||||
"github.com/theater/picomap/lib/msgpack"
|
||||
)
|
||||
|
||||
var HashKey = [8]byte{}
|
||||
|
||||
type RebootingBootsel struct{}
|
||||
|
||||
type Envelope struct {
|
||||
Checksum uint32
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
func init() {
|
||||
msgpack.RegisterExt(0, (*Envelope)(nil))
|
||||
msgpack.RegisterExt(1, (*RebootingBootsel)(nil))
|
||||
}
|
||||
|
||||
func DecodeMessage(data []byte) (any, error) {
|
||||
var env Envelope
|
||||
if err := msgpack.Unmarshal(data, &env); err != nil {
|
||||
return nil, fmt.Errorf("decode envelope: %w", err)
|
||||
}
|
||||
|
||||
expected := halfsiphash.Sum32(env.Payload, HashKey)
|
||||
if env.Checksum != expected {
|
||||
return nil, fmt.Errorf("checksum mismatch: got %08x, want %08x", env.Checksum, expected)
|
||||
}
|
||||
|
||||
var inner any
|
||||
if err := msgpack.Unmarshal(env.Payload, &inner); err != nil {
|
||||
return nil, fmt.Errorf("decode inner: %w", err)
|
||||
}
|
||||
return inner, nil
|
||||
}
|
||||
Reference in New Issue
Block a user