-
Notifications
You must be signed in to change notification settings - Fork 210
/
block.go
241 lines (199 loc) · 6.61 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
package types
import (
"bytes"
"fmt"
"math/big"
"sort"
"github.com/google/go-cmp/cmp"
"github.com/spacemeshos/go-scale"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/log"
)
const (
// BlockIDSize in bytes.
// FIXME(dshulyak) why do we cast to hash32 when returning bytes?
// probably required for fetching by hash between peers.
BlockIDSize = Hash32Length
)
//go:generate scalegen -types Block,InnerBlock,RatNum,AnyReward,Certificate,CertifyMessage,CertifyContent
// BlockID is a 20-byte blake3 sum of the serialized block used to identify a Block.
type BlockID Hash20
// EmptyBlockID is a canonical empty BlockID.
var EmptyBlockID = BlockID{}
// NewExistingBlock creates a block from existing data.
func NewExistingBlock(id BlockID, inner InnerBlock) *Block {
return &Block{blockID: id, InnerBlock: inner}
}
// EncodeScale implements scale codec interface.
func (id *BlockID) EncodeScale(e *scale.Encoder) (int, error) {
return scale.EncodeByteArray(e, id[:])
}
// DecodeScale implements scale codec interface.
func (id *BlockID) DecodeScale(d *scale.Decoder) (int, error) {
return scale.DecodeByteArray(d, id[:])
}
func (id *BlockID) IsEmpty() bool {
return *id == EmptyBlockID
}
// Block contains the content of a layer on the mesh history.
type Block struct {
InnerBlock
// the following fields are kept private and from being serialized
blockID BlockID
}
func (b Block) Equal(other Block) bool {
return cmp.Equal(b.InnerBlock, other.InnerBlock)
}
// InnerBlock contains the transactions and rewards of a block.
type InnerBlock struct {
LayerIndex LayerID
TickHeight uint64
Rewards []AnyReward `scale:"max=500"`
TxIDs []TransactionID `scale:"max=100000"`
}
// RatNum represents a rational number with the numerator and denominator.
// note: RatNum aims to be a generic representation of a rational number and parse-able by
// different programming languages.
// for doing math around weight inside go-spacemesh codebase, use util.Weight.
type RatNum struct {
Num, Denom uint64
}
// String implements fmt.Stringer interface for RatNum.
func (r *RatNum) String() string {
return fmt.Sprintf("%d/%d", r.Num, r.Denom)
}
// ToBigRat creates big.Rat instance.
func (r *RatNum) ToBigRat() *big.Rat {
return new(big.Rat).SetFrac(
new(big.Int).SetUint64(r.Num),
new(big.Int).SetUint64(r.Denom),
)
}
func RatNumFromBigRat(r *big.Rat) RatNum {
return RatNum{Num: r.Num().Uint64(), Denom: r.Denom().Uint64()}
}
// AnyReward contains the reward information by ATXID.
type AnyReward struct {
AtxID ATXID
Weight RatNum
}
// CoinbaseReward contains the reward information by coinbase, used as an interface to VM.
type CoinbaseReward struct {
Coinbase Address
Weight RatNum
}
// Initialize calculates and sets the Block's cached blockID.
func (b *Block) Initialize() {
b.blockID = BlockID(CalcHash32(b.Bytes()).ToHash20())
}
// Bytes returns the serialization of the InnerBlock.
func (b *Block) Bytes() []byte {
data, err := codec.Encode(&b.InnerBlock)
if err != nil {
log.Panic("failed to serialize block: %v", err)
}
return data
}
// ID returns the BlockID.
func (b *Block) ID() BlockID {
return b.blockID
}
// ToVote creates Vote struct from block.
func (b *Block) ToVote() Vote {
return Vote{ID: b.ID(), LayerID: b.LayerIndex, Height: b.TickHeight}
}
// MarshalLogObject implements logging encoder for Block.
func (b *Block) MarshalLogObject(encoder log.ObjectEncoder) error {
encoder.AddString("block_id", b.ID().String())
encoder.AddUint32("layer_id", b.LayerIndex.Uint32())
encoder.AddUint64("tick_height", b.TickHeight)
encoder.AddInt("num_tx", len(b.TxIDs))
encoder.AddInt("num_rewards", len(b.Rewards))
return nil
}
// Bytes returns the BlockID as a byte slice.
func (id BlockID) Bytes() []byte {
return id.AsHash32().Bytes()
}
// AsHash32 returns a Hash32 whose first 20 bytes are the bytes of this BlockID, it is right-padded with zeros.
func (id BlockID) AsHash32() Hash32 {
return Hash20(id).ToHash32()
}
// Field returns a log field. Implements the LoggableField interface.
func (id BlockID) Field() log.Field {
return log.String("block_id", id.String())
}
// String implements the Stringer interface.
func (id BlockID) String() string {
return id.AsHash32().ShortString()
}
// Compare returns true if other (the given BlockID) is less than this BlockID, by lexicographic comparison.
func (id BlockID) Compare(other BlockID) bool {
return bytes.Compare(id.Bytes(), other.Bytes()) < 0
}
// BlockIDsToHashes turns a list of BlockID into their Hash32 representation.
func BlockIDsToHashes(ids []BlockID) []Hash32 {
hashes := make([]Hash32, 0, len(ids))
for _, id := range ids {
hashes = append(hashes, id.AsHash32())
}
return hashes
}
type blockIDs []BlockID
func (ids blockIDs) MarshalLogArray(encoder log.ArrayEncoder) error {
for i := range ids {
encoder.AppendString(ids[i].String())
}
return nil
}
// SortBlockIDs sorts a list of BlockID in lexicographic order, in-place.
func SortBlockIDs(ids blockIDs) []BlockID {
sort.Slice(ids, func(i, j int) bool { return ids[i].Compare(ids[j]) })
return ids
}
// BlockIdsField returns a list of loggable fields for a given list of BlockID.
func BlockIdsField(ids blockIDs) log.Field {
return log.Array("block_ids", ids)
}
// ToBlockIDs returns a slice of BlockID corresponding to the given list of Block.
func ToBlockIDs(blocks []*Block) []BlockID {
ids := make([]BlockID, 0, len(blocks))
for _, b := range blocks {
ids = append(ids, b.ID())
}
return ids
}
// BlockContextualValidity represents the contextual validity of a block.
type BlockContextualValidity struct {
ID BlockID
Validity bool
}
// Certificate represents a certified block.
type Certificate struct {
BlockID BlockID
Signatures []CertifyMessage `scale:"max=1000"` // the max. size depends on HARE.N config parameter + some safety buffer
}
// CertifyMessage is generated by a node that's eligible to certify the hare output and is gossiped to the network.
type CertifyMessage struct {
CertifyContent
Signature EdSignature
SmesherID NodeID
}
// CertifyContent is actual content the node would sign to certify a hare output.
type CertifyContent struct {
LayerID LayerID
BlockID BlockID
// EligibilityCnt is the number of eligibility of a NodeID on the given Layer
// as a hare output certifier.
EligibilityCnt uint16
// Proof is the role proof for being a hare output certifier on the given Layer.
Proof VrfSignature
}
// Bytes returns the actual data being signed in a CertifyMessage.
func (cm *CertifyMessage) Bytes() []byte {
data, err := codec.Encode(&cm.CertifyContent)
if err != nil {
log.Panic("failed to serialize certify msg: %v", err)
}
return data
}