/
messagefactory.go
265 lines (210 loc) · 9.23 KB
/
messagefactory.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
package tangle
import (
"fmt"
"sync"
"time"
"github.com/cockroachdb/errors"
"github.com/iotaledger/hive.go/crypto/ed25519"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/identity"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/goshimmer/packages/clock"
"github.com/iotaledger/goshimmer/packages/ledgerstate"
"github.com/iotaledger/goshimmer/packages/tangle/payload"
)
const storeSequenceInterval = 100
// region MessageFactory ///////////////////////////////////////////////////////////////////////////////////////////////
// MessageFactory acts as a factory to create new messages.
type MessageFactory struct {
Events *MessageFactoryEvents
tangle *Tangle
sequence *kvstore.Sequence
localIdentity *identity.LocalIdentity
selector TipSelector
powTimeout time.Duration
worker Worker
workerMutex sync.RWMutex
issuanceMutex sync.Mutex
}
// NewMessageFactory creates a new message factory.
func NewMessageFactory(tangle *Tangle, selector TipSelector) *MessageFactory {
sequence, err := kvstore.NewSequence(tangle.Options.Store, []byte(DBSequenceNumber), storeSequenceInterval)
if err != nil {
panic(fmt.Sprintf("could not create message sequence number: %v", err))
}
return &MessageFactory{
Events: &MessageFactoryEvents{
MessageConstructed: events.NewEvent(messageEventHandler),
Error: events.NewEvent(events.ErrorCaller),
},
tangle: tangle,
sequence: sequence,
localIdentity: tangle.Options.Identity,
selector: selector,
worker: ZeroWorker,
powTimeout: 0 * time.Second,
}
}
// SetWorker sets the PoW worker to be used for the messages.
func (f *MessageFactory) SetWorker(worker Worker) {
f.workerMutex.Lock()
defer f.workerMutex.Unlock()
f.worker = worker
}
// SetTimeout sets the timeout for PoW.
func (f *MessageFactory) SetTimeout(timeout time.Duration) {
f.powTimeout = timeout
}
// IssuePayload creates a new message including sequence number and tip selection and returns it.
// It also triggers the MessageConstructed event once it's done, which is for example used by the plugins to listen for
// messages that shall be attached to the tangle.
func (f *MessageFactory) IssuePayload(p payload.Payload, parentsCount ...int) (*Message, error) {
payloadLen := len(p.Bytes())
if payloadLen > payload.MaxSize {
err := fmt.Errorf("maximum payload size of %d bytes exceeded", payloadLen)
f.Events.Error.Trigger(err)
return nil, err
}
f.issuanceMutex.Lock()
sequenceNumber, err := f.sequence.Next()
if err != nil {
err = errors.Errorf("could not create sequence number: %w", err)
f.Events.Error.Trigger(err)
f.issuanceMutex.Unlock()
return nil, err
}
countStrongParents := 2
if len(parentsCount) > 0 {
countStrongParents = parentsCount[0]
}
strongParents, weakParents, err := f.selector.Tips(p, countStrongParents, 2)
if err != nil {
err = errors.Errorf("tips could not be selected: %w", err)
f.Events.Error.Trigger(err)
f.issuanceMutex.Unlock()
return nil, err
}
issuingTime := f.getIssuingTime(strongParents, weakParents)
issuerPublicKey := f.localIdentity.PublicKey()
// do the PoW
startTime := time.Now()
nonce, err := f.doPOW(strongParents, weakParents, issuingTime, issuerPublicKey, sequenceNumber, p)
for err != nil && time.Since(startTime) < f.powTimeout {
if p.Type() != ledgerstate.TransactionType {
strongParents, weakParents, err = f.selector.Tips(p, countStrongParents, 2)
if err != nil {
err = errors.Errorf("tips could not be selected: %w", err)
f.Events.Error.Trigger(err)
f.issuanceMutex.Unlock()
return nil, err
}
}
issuingTime = f.getIssuingTime(strongParents, weakParents)
nonce, err = f.doPOW(strongParents, weakParents, issuingTime, issuerPublicKey, sequenceNumber, p)
}
if err != nil {
err = errors.Errorf("pow failed: %w", err)
f.Events.Error.Trigger(err)
f.issuanceMutex.Unlock()
return nil, err
}
f.issuanceMutex.Unlock()
// create the signature
signature := f.sign(strongParents, weakParents, issuingTime, issuerPublicKey, sequenceNumber, p, nonce)
msg := NewMessage(
strongParents,
weakParents,
issuingTime,
issuerPublicKey,
sequenceNumber,
p,
nonce,
signature,
)
f.Events.MessageConstructed.Trigger(msg)
return msg, nil
}
func (f *MessageFactory) getIssuingTime(strongParents, weakParents MessageIDs) time.Time {
issuingTime := clock.SyncedTime()
// due to the ParentAge check we must ensure that we set the right issuing time.
for _, parent := range strongParents {
f.tangle.Storage.Message(parent).Consume(func(msg *Message) {
if msg.ID() != EmptyMessageID && !msg.IssuingTime().Before(issuingTime) {
issuingTime = msg.IssuingTime()
}
})
}
for _, parent := range weakParents {
f.tangle.Storage.Message(parent).Consume(func(msg *Message) {
if msg.ID() != EmptyMessageID && !msg.IssuingTime().Before(issuingTime) {
issuingTime = msg.IssuingTime()
}
})
}
return issuingTime
}
// Shutdown closes the MessageFactory and persists the sequence number.
func (f *MessageFactory) Shutdown() {
if err := f.sequence.Release(); err != nil {
f.Events.Error.Trigger(fmt.Errorf("could not release message sequence number: %w", err))
}
}
func (f *MessageFactory) doPOW(strongParents []MessageID, weakParents []MessageID, issuingTime time.Time, key ed25519.PublicKey, seq uint64, payload payload.Payload) (uint64, error) {
// create a dummy message to simplify marshaling
dummy := NewMessage(strongParents, weakParents, issuingTime, key, seq, payload, 0, ed25519.EmptySignature).Bytes()
f.workerMutex.RLock()
defer f.workerMutex.RUnlock()
return f.worker.DoPOW(dummy)
}
func (f *MessageFactory) sign(strongParents []MessageID, weakParents []MessageID, issuingTime time.Time, key ed25519.PublicKey, seq uint64, payload payload.Payload, nonce uint64) ed25519.Signature {
// create a dummy message to simplify marshaling
dummy := NewMessage(strongParents, weakParents, issuingTime, key, seq, payload, nonce, ed25519.EmptySignature)
dummyBytes := dummy.Bytes()
contentLength := len(dummyBytes) - len(dummy.Signature())
return f.localIdentity.Sign(dummyBytes[:contentLength])
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region MessageFactoryEvents /////////////////////////////////////////////////////////////////////////////////////////
// MessageFactoryEvents represents events happening on a message factory.
type MessageFactoryEvents struct {
// Fired when a message is built including tips, sequence number and other metadata.
MessageConstructed *events.Event
// Fired when an error occurred.
Error *events.Event
}
func messageEventHandler(handler interface{}, params ...interface{}) {
handler.(func(*Message))(params[0].(*Message))
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region TipSelector //////////////////////////////////////////////////////////////////////////////////////////////////
// A TipSelector selects two tips, parent2 and parent1, for a new message to attach to.
type TipSelector interface {
Tips(p payload.Payload, countStrongParents, countWeakParents int) (strongParents, weakParents MessageIDs, err error)
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region TipSelectorFunc //////////////////////////////////////////////////////////////////////////////////////////////
// The TipSelectorFunc type is an adapter to allow the use of ordinary functions as tip selectors.
type TipSelectorFunc func(p payload.Payload, countStrongParents, countWeakParents int) (strongParents, weakParents MessageIDs, err error)
// Tips calls f().
func (f TipSelectorFunc) Tips(p payload.Payload, countStrongParents, countWeakParents int) (strongParents, weakParents MessageIDs, err error) {
return f(p, countStrongParents, countWeakParents)
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region Worker ///////////////////////////////////////////////////////////////////////////////////////////////////////
// A Worker performs the PoW for the provided message in serialized byte form.
type Worker interface {
DoPOW([]byte) (nonce uint64, err error)
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region WorkerFunc ///////////////////////////////////////////////////////////////////////////////////////////////////
// The WorkerFunc type is an adapter to allow the use of ordinary functions as a PoW performer.
type WorkerFunc func([]byte) (uint64, error)
// DoPOW calls f(msg).
func (f WorkerFunc) DoPOW(msg []byte) (uint64, error) {
return f(msg)
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region ZeroWorker ///////////////////////////////////////////////////////////////////////////////////////////////////
// ZeroWorker is a PoW worker that always returns 0 as the nonce.
var ZeroWorker = WorkerFunc(func([]byte) (uint64, error) { return 0, nil })
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////