/
block.go
275 lines (259 loc) · 7.91 KB
/
block.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package codec
import (
"bytes"
"encoding/binary"
"strconv"
"time"
"blockwatch.cc/tzgo/tezos"
)
// BlockHeader represents a Tenderbake compatible block header
type BlockHeader struct {
Level int32 `json:"level"`
Proto byte `json:"proto"`
Predecessor tezos.BlockHash `json:"predecessor"`
Timestamp time.Time `json:"timestamp"`
ValidationPass byte `json:"validation_pass"`
OperationsHash tezos.OpListListHash `json:"operations_hash"`
Fitness []tezos.HexBytes `json:"fitness"`
Context tezos.ContextHash `json:"context"`
PayloadHash tezos.PayloadHash `json:"payload_hash"`
PayloadRound int `json:"payload_round"`
ProofOfWorkNonce tezos.HexBytes `json:"proof_of_work_nonce"`
SeedNonceHash tezos.NonceHash `json:"seed_nonce_hash"`
LbVote tezos.FeatureVote `json:"liquidity_baking_toggle_vote"`
AiVote tezos.FeatureVote `json:"adaptive_issuance_vote"`
Signature tezos.Signature `json:"signature"`
ChainId *tezos.ChainIdHash `json:"-"` // remote signer use only
}
// Bytes serializes the block header into binary form. When no signature is set, the
// result can be used as input for signing, if a signature is set the result is
// ready for broadcast.
func (h BlockHeader) Bytes() []byte {
buf := bytes.NewBuffer(nil)
_ = h.EncodeBuffer(buf)
return buf.Bytes()
}
// WatermarkedBytes serializes the block header and prefixes it with a watermark.
// This format is only used for signing.
func (h BlockHeader) WatermarkedBytes() []byte {
buf := bytes.NewBuffer(nil)
buf.WriteByte(TenderbakeBlockWatermark)
buf.Write(h.ChainId.Bytes())
_ = h.EncodeBuffer(buf)
return buf.Bytes()
}
// Digest returns a 32 byte blake2b hash for signing the block header. The pre-image
// is binary serialized (without signature) and prefixed with a watermark byte.
func (h BlockHeader) Digest() []byte {
d := tezos.Digest(h.WatermarkedBytes())
return d[:]
}
// Hash calculates the block hash. For the hash to be correct, the block
// must contain a valid signature.
func (h *BlockHeader) Hash() (s tezos.BlockHash) {
d := tezos.Digest(h.Bytes())
copy(s[:], d[:])
return
}
// Sign signs the block header using a private key and generates a generic signature.
// If a valid signature already exists, this function is a noop.
func (h *BlockHeader) Sign(key tezos.PrivateKey) error {
if h.Signature.IsValid() {
return nil
}
sig, err := key.Sign(h.Digest())
sig.Type = tezos.SignatureTypeGeneric
if err != nil {
return err
}
h.Signature = sig
return nil
}
// WithChainId sets chain_id for this block to id. Use this only for remote signing
// of blocks as it creates an invalid binary encoding otherwise.
func (h *BlockHeader) WithChainId(id tezos.ChainIdHash) *BlockHeader {
clone := id.Clone()
h.ChainId = &clone
return h
}
// WithSignature adds an externally created signature to the block header. Converts
// any non-generic signature first. No signature validation is performed, it is
// assumed the signature is correct.
func (h *BlockHeader) WithSignature(sig tezos.Signature) *BlockHeader {
sig = sig.Clone()
sig.Type = tezos.SignatureTypeGeneric
h.Signature = sig
return h
}
func (h BlockHeader) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(nil)
buf.WriteByte('{')
buf.WriteString(`"level":`)
buf.WriteString(strconv.FormatInt(int64(h.Level), 10))
buf.WriteString(`,"proto":`)
buf.WriteString(strconv.Itoa(int(h.Proto)))
buf.WriteString(`,"predecessor":`)
buf.WriteString(strconv.Quote(h.Predecessor.String()))
buf.WriteString(`,"timestamp":`)
buf.WriteString(strconv.Quote(h.Timestamp.UTC().Format("2006-01-02T15:04:05Z")))
buf.WriteString(`,"validation_pass":`)
buf.WriteString(strconv.Itoa(int(h.ValidationPass)))
buf.WriteString(`,"operations_hash":`)
buf.WriteString(strconv.Quote(h.OperationsHash.String()))
buf.WriteString(`,"fitness":[`)
for i, v := range h.Fitness {
if i > 0 {
buf.WriteByte(',')
}
buf.WriteString(strconv.Quote(v.String()))
}
buf.WriteString(`],"context":`)
buf.WriteString(strconv.Quote(h.Context.String()))
buf.WriteString(`,"payload_hash":`)
buf.WriteString(strconv.Quote(h.PayloadHash.String()))
buf.WriteString(`,"payload_round":`)
buf.WriteString(strconv.Itoa(h.PayloadRound))
buf.WriteString(`,"proof_of_work_nonce":`)
buf.WriteString(strconv.Quote(h.ProofOfWorkNonce.String()))
if h.SeedNonceHash.IsValid() {
buf.WriteString(`,"seed_nonce_hash":`)
buf.WriteString(strconv.Quote(h.SeedNonceHash.String()))
}
buf.WriteString(`,"liquidity_baking_toggle_vote":`)
buf.WriteString(strconv.Quote(h.LbVote.String()))
buf.WriteString(`,"adaptive_issuance_vote":`)
buf.WriteString(strconv.Quote(h.AiVote.String()))
if h.Signature.IsValid() {
buf.WriteString(`,"signature":`)
buf.WriteString(strconv.Quote(h.Signature.String()))
}
buf.WriteByte('}')
return buf.Bytes(), nil
}
func (h *BlockHeader) EncodeBuffer(buf *bytes.Buffer) error {
binary.Write(buf, enc, h.Level)
buf.WriteByte(h.Proto)
buf.Write(h.Predecessor.Bytes())
binary.Write(buf, enc, h.Timestamp.Unix())
buf.WriteByte(h.ValidationPass)
buf.Write(h.OperationsHash.Bytes())
var fitnessLen int
for _, v := range h.Fitness {
fitnessLen += len(v)
}
binary.Write(buf, enc, uint32(fitnessLen+4*len(h.Fitness)))
for _, v := range h.Fitness {
binary.Write(buf, enc, uint32(len(v)))
buf.Write(v)
}
buf.Write(h.Context.Bytes())
buf.Write(h.PayloadHash.Bytes())
binary.Write(buf, enc, uint32(h.PayloadRound))
buf.Write(h.ProofOfWorkNonce)
if h.SeedNonceHash.IsValid() {
buf.WriteByte(0xff)
buf.Write(h.SeedNonceHash.Bytes())
} else {
buf.WriteByte(0x0)
}
// BROKEN: merging multiple vote flags is undocumented
buf.WriteByte(h.LbVote.Tag() | (h.AiVote.Tag() << 2))
if h.Signature.IsValid() {
buf.Write(h.Signature.Data) // raw, no tag!
}
return nil
}
func (h *BlockHeader) DecodeBuffer(buf *bytes.Buffer) (err error) {
h.Level, err = readInt32(buf.Next(4))
if err != nil {
return
}
h.Proto, err = readByte(buf.Next(1))
if err != nil {
return
}
if err = h.Predecessor.UnmarshalBinary(buf.Next(32)); err != nil {
return
}
var i64 int64
i64, err = readInt64(buf.Next(8))
if err != nil {
return
}
h.Timestamp = time.Unix(i64, 0).UTC()
h.ValidationPass, err = readByte(buf.Next(1))
if err != nil {
return
}
if err = h.OperationsHash.UnmarshalBinary(buf.Next(32)); err != nil {
return
}
var l int32
l, err = readInt32(buf.Next(4))
if err != nil {
return
}
h.Fitness = make([]tezos.HexBytes, 0)
for l > 0 {
var n int32
n, err = readInt32(buf.Next(4))
if err != nil {
return
}
b := make([]byte, int(n))
copy(b, buf.Next(int(n)))
h.Fitness = append(h.Fitness, b)
l -= n + 4
}
if err = h.Context.UnmarshalBinary(buf.Next(32)); err != nil {
return
}
if err = h.PayloadHash.UnmarshalBinary(buf.Next(32)); err != nil {
return
}
l, err = readInt32(buf.Next(4))
if err != nil {
return
}
h.PayloadRound = int(l)
h.ProofOfWorkNonce = make([]byte, 8)
copy(h.ProofOfWorkNonce[:], buf.Next(8))
var ok bool
ok, err = readBool(buf.Next(1))
if err != nil {
return
}
if ok {
if err = h.SeedNonceHash.UnmarshalBinary(buf.Next(32)); err != nil {
return
}
}
// BROKEN: merging multiple vote flags is undocumented
b := buf.Next(1)
if len(b) > 0 {
if err = h.LbVote.UnmarshalBinary([]byte{b[0] & 3}); err != nil {
return
}
if err = h.AiVote.UnmarshalBinary([]byte{(b[0] >> 2) & 3}); err != nil {
return
}
}
// conditionally read signature
if buf.Len() > 0 {
err = h.Signature.UnmarshalBinary(buf.Next(64))
if err != nil {
return
}
}
return nil
}
func (h BlockHeader) MarshalBinary() ([]byte, error) {
buf := bytes.NewBuffer(nil)
err := h.EncodeBuffer(buf)
return buf.Bytes(), err
}
func (h *BlockHeader) UnmarshalBinary(data []byte) error {
return h.DecodeBuffer(bytes.NewBuffer(data))
}