diff options
author | Linus Nordberg <linus@nordberg.se> | 2021-05-25 11:29:29 +0200 |
---|---|---|
committer | Linus Nordberg <linus@nordberg.se> | 2021-05-25 11:29:29 +0200 |
commit | f9aae584c787950e84cf3b098290a0c73330d8ac (patch) | |
tree | d3a018493954529794de3c21c9f4f6b0c846a925 /types/trunnel.go | |
parent | 533f683ef1ae999c2fdc0086cbc3de4e675d1e33 (diff) | |
parent | 6a20aec8e8a93ce11f8b940659f49c889f94aef1 (diff) |
Merge branch 'design' of github.com:system-transparency/stfe into design
Diffstat (limited to 'types/trunnel.go')
-rw-r--r-- | types/trunnel.go | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/types/trunnel.go b/types/trunnel.go new file mode 100644 index 0000000..72ae68d --- /dev/null +++ b/types/trunnel.go @@ -0,0 +1,57 @@ +package types + +import ( + "encoding/binary" + "fmt" +) + +const ( + // MessageSize is the number of bytes in a Trunnel-encoded leaf message + MessageSize = 8 + HashSize + // LeafSize is the number of bytes in a Trunnel-encoded leaf + LeafSize = MessageSize + SignatureSize + HashSize +) + +// Marshal returns a Trunnel-encoded message +func (m *Message) Marshal() []byte { + buf := make([]byte, MessageSize) + binary.BigEndian.PutUint64(buf, m.ShardHint) + copy(buf[8:], m.Checksum[:]) + return buf +} + +// Marshal returns a Trunnel-encoded leaf +func (l *Leaf) Marshal() []byte { + buf := l.Message.Marshal() + buf = append(buf, l.SigIdent.Signature[:]...) + buf = append(buf, l.SigIdent.KeyHash[:]...) + return buf +} + +// Marshal returns a Trunnel-encoded tree head +func (th *TreeHead) Marshal() []byte { + buf := make([]byte, 8+8+HashSize) + binary.BigEndian.PutUint64(buf[0:8], th.Timestamp) + binary.BigEndian.PutUint64(buf[8:16], th.TreeSize) + copy(buf[16:], th.RootHash[:]) + return buf +} + +// Unmarshal parses the Trunnel-encoded buffer as a leaf +func (l *Leaf) Unmarshal(buf []byte) error { + if len(buf) != LeafSize { + return fmt.Errorf("invalid leaf size: %v", len(buf)) + } + // Shard hint + l.ShardHint = binary.BigEndian.Uint64(buf) + offset := 8 + // Checksum + copy(l.Checksum[:], buf[offset:offset+HashSize]) + offset += HashSize + // Signature + copy(l.Signature[:], buf[offset:offset+SignatureSize]) + offset += SignatureSize + // KeyHash + copy(l.KeyHash[:], buf[offset:]) + return nil +} |