generated from rollkit/template-da-repo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
serialization.go
60 lines (51 loc) · 1.28 KB
/
serialization.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package sequencing
import (
"crypto/sha256"
pbseq "github.com/rollkit/go-sequencing/types/pb/sequencing"
)
// ToProto serializes a batch to a protobuf message.
func (batch *Batch) ToProto() *pbseq.Batch {
return &pbseq.Batch{Transactions: txsToByteSlices(batch.Transactions)}
}
// FromProto deserializes a batch from a protobuf message.
func (batch *Batch) FromProto(pb *pbseq.Batch) {
batch.Transactions = byteSlicesToTxs(pb.Transactions)
}
func txsToByteSlices(txs []Tx) [][]byte {
if txs == nil {
return nil
}
bytes := make([][]byte, len(txs))
copy(bytes, txs)
return bytes
}
func byteSlicesToTxs(bytes [][]byte) []Tx {
if len(bytes) == 0 {
return nil
}
txs := make([]Tx, len(bytes))
copy(txs, bytes)
return txs
}
// Marshal serializes a batch to a byte slice.
func (batch *Batch) Marshal() ([]byte, error) {
return batch.ToProto().Marshal()
}
// Unmarshal deserializes a batch from a byte slice.
func (batch *Batch) Unmarshal(data []byte) error {
var pb pbseq.Batch
if err := pb.Unmarshal(data); err != nil {
return err
}
batch.FromProto(&pb)
return nil
}
// Hash returns the hash of a batch.
func (batch *Batch) Hash() ([]byte, error) {
batchBytes, err := batch.Marshal()
if err != nil {
return nil, err
}
hash := sha256.Sum256(batchBytes)
return hash[:], nil
}