/
transaction_service.go
476 lines (434 loc) · 14.2 KB
/
transaction_service.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package grpcserver
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
pb "github.com/spacemeshos/api/release/go/spacemesh/v1"
"go.uber.org/zap"
"google.golang.org/genproto/googleapis/rpc/code"
rpcstatus "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/events"
"github.com/spacemeshos/go-spacemesh/genvm/core"
"github.com/spacemeshos/go-spacemesh/p2p/pubsub"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/transactions"
)
// TransactionService exposes transaction data, and a submit tx endpoint.
type TransactionService struct {
db *sql.Database
publisher pubsub.Publisher // P2P Swarm
mesh meshAPI // Mesh
conState conservativeState
syncer syncer
txHandler txValidator
}
// RegisterService registers this service with a grpc server instance.
func (s TransactionService) RegisterService(server *grpc.Server) {
pb.RegisterTransactionServiceServer(server, s)
}
func (s TransactionService) RegisterHandlerService(mux *runtime.ServeMux) error {
return pb.RegisterTransactionServiceHandlerServer(context.Background(), mux, s)
}
// String returns the name of this service.
func (s TransactionService) String() string {
return "TransactionService"
}
// NewTransactionService creates a new grpc service using config data.
func NewTransactionService(
db *sql.Database,
publisher pubsub.Publisher,
msh meshAPI,
conState conservativeState,
syncer syncer,
txHandler txValidator,
) *TransactionService {
return &TransactionService{
db: db,
publisher: publisher,
mesh: msh,
conState: conState,
syncer: syncer,
txHandler: txHandler,
}
}
func (s TransactionService) ParseTransaction(
ctx context.Context,
in *pb.ParseTransactionRequest,
) (*pb.ParseTransactionResponse, error) {
if len(in.Transaction) == 0 {
return nil, status.Error(codes.InvalidArgument, "empty transaction")
}
raw := types.NewRawTx(in.Transaction)
req := s.conState.Validation(raw)
header, err := req.Parse()
if errors.Is(err, core.ErrNotSpawned) {
return nil, status.Error(codes.NotFound, "account is not spawned")
} else if errors.Is(err, core.ErrMalformed) {
return nil, status.Error(codes.InvalidArgument, err.Error())
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if in.Verify && !req.Verify() {
return nil, status.Error(codes.InvalidArgument, "signature is invalid")
}
tx := types.Transaction{RawTx: raw, TxHeader: header}
return &pb.ParseTransactionResponse{Tx: castTransaction(&tx)}, nil
}
// SubmitTransaction allows a new tx to be submitted.
func (s TransactionService) SubmitTransaction(
ctx context.Context,
in *pb.SubmitTransactionRequest,
) (*pb.SubmitTransactionResponse, error) {
if len(in.Transaction) == 0 {
return nil, status.Error(codes.InvalidArgument, "`Transaction` payload empty")
}
if !s.syncer.IsSynced(ctx) {
return nil, status.Error(
codes.FailedPrecondition,
"Cannot submit transaction, node is not in sync yet, try again later",
)
}
if err := s.txHandler.VerifyAndCacheTx(ctx, in.Transaction); err != nil {
return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("Failed to verify transaction: %s", err.Error()))
}
if err := s.publisher.Publish(ctx, pubsub.TxProtocol, in.Transaction); err != nil {
return nil, status.Error(codes.Internal, fmt.Sprintf("Failed to publish transaction: %s", err.Error()))
}
raw := types.NewRawTx(in.Transaction)
return &pb.SubmitTransactionResponse{
Status: &rpcstatus.Status{Code: int32(code.Code_OK)},
Txstate: &pb.TransactionState{
Id: &pb.TransactionId{Id: raw.ID[:]},
State: pb.TransactionState_TRANSACTION_STATE_MEMPOOL,
},
}, nil
}
// Get transaction and status for a given txid. It's not an error if we cannot find the tx,
// we just return all nils.
func (s TransactionService) getTransactionAndStatus(
txID types.TransactionID,
) (*types.Transaction, pb.TransactionState_TransactionState) {
var state pb.TransactionState_TransactionState
tx, err := s.conState.GetMeshTransaction(txID)
if err != nil {
return nil, state
}
switch tx.State {
case types.MEMPOOL:
state = pb.TransactionState_TRANSACTION_STATE_MEMPOOL
case types.APPLIED:
state = pb.TransactionState_TRANSACTION_STATE_PROCESSED
default:
state = pb.TransactionState_TRANSACTION_STATE_UNSPECIFIED
}
return &tx.Transaction, state
}
// TransactionsState returns current tx data for one or more txs.
func (s TransactionService) TransactionsState(
_ context.Context,
in *pb.TransactionsStateRequest,
) (*pb.TransactionsStateResponse, error) {
if in.TransactionId == nil || len(in.TransactionId) == 0 {
return nil, status.Error(codes.InvalidArgument, "`TransactionId` must include one or more transaction IDs")
}
res := &pb.TransactionsStateResponse{}
for _, pbtxid := range in.TransactionId {
// Convert the incoming txid into a known type
txid := types.TransactionID{}
copy(txid[:], pbtxid.Id)
// Look up data for this tx. If it's unknown to us, status will be zero (unspecified).
tx, txstate := s.getTransactionAndStatus(txid)
res.TransactionsState = append(res.TransactionsState, &pb.TransactionState{
Id: pbtxid,
State: txstate,
})
if in.IncludeTransactions {
if tx != nil {
res.Transactions = append(res.Transactions, castTransaction(tx))
} else {
// If the tx is unknown to us, add an empty placeholder
res.Transactions = append(res.Transactions, &pb.Transaction{})
}
}
}
return res, nil
}
// STREAMS
// TransactionsStateStream exposes a stream of tx data.
func (s TransactionService) TransactionsStateStream(
in *pb.TransactionsStateStreamRequest,
stream pb.TransactionService_TransactionsStateStreamServer,
) error {
if in.TransactionId == nil || len(in.TransactionId) == 0 {
return status.Error(codes.InvalidArgument, "`TransactionId` must include one or more transaction IDs")
}
// The tx channel tells us about newly received and newly created transactions
// The layer channel tells us about status updates
var (
txCh <-chan events.Transaction
layerCh <-chan events.LayerUpdate
txBufFull, layerBufFull <-chan struct{}
)
if txsSubscription := events.SubscribeTxs(); txsSubscription != nil {
txCh, txBufFull = consumeEvents[events.Transaction](stream.Context(), txsSubscription)
}
if layersSubscription := events.SubscribeLayers(); layersSubscription != nil {
layerCh, layerBufFull = consumeEvents[events.LayerUpdate](stream.Context(), layersSubscription)
}
if err := stream.SendHeader(metadata.MD{}); err != nil {
return status.Errorf(codes.Unavailable, "can't send header")
}
for {
select {
case <-txBufFull:
ctxzap.Info(stream.Context(), "tx buffer is full, shutting down")
return status.Error(codes.Canceled, errTxBufferFull)
case <-layerBufFull:
ctxzap.Info(stream.Context(), "layer buffer is full, shutting down")
return status.Error(codes.Canceled, errLayerBufferFull)
case tx := <-txCh:
// Filter
for _, txid := range in.TransactionId {
if bytes.Equal(tx.Transaction.ID.Bytes(), txid.Id) {
// If the tx was just invalidated, we already know its state.
// If not, read it from the database.
var txstate pb.TransactionState_TransactionState
if tx.Valid {
_, txstate = s.getTransactionAndStatus(tx.Transaction.ID)
} else {
txstate = pb.TransactionState_TRANSACTION_STATE_CONFLICTING
}
res := &pb.TransactionsStateStreamResponse{
TransactionState: &pb.TransactionState{
Id: txid,
State: txstate,
},
}
if in.IncludeTransactions {
res.Transaction = castTransaction(tx.Transaction)
}
if err := stream.Send(res); err != nil {
return fmt.Errorf("send stream: %w", err)
}
// Don't match on any other transactions
break
}
}
case layer := <-layerCh:
// Transaction objects do not have an associated status. The status we assign them here is based on the
// status of the layer (really, the block) they're contained in. Here, we receive updates to layer status.
// In order to update tx status, we have to read every transaction in the layer.
// TODO: this is inefficient, come up with a more optimal way of doing this
// TODO: tx status should depend upon block status, not layer status
// In order to read transactions, we first need to read layer blocks
layerObj, err := s.mesh.GetLayer(layer.LayerID)
if err != nil {
ctxzap.Error(
stream.Context(),
"error reading layer data for updated layer",
layer.LayerID.Field().Zap(),
zap.Error(err),
)
return status.Error(codes.Internal, "error reading layer data")
}
// Filter for any matching transactions in the reported layer
for _, b := range layerObj.Blocks() {
blockTXIDSet := make(map[types.TransactionID]struct{})
// create a set for the block transaction IDs
for _, txid := range b.TxIDs {
blockTXIDSet[txid] = struct{}{}
}
var txstate pb.TransactionState_TransactionState
switch layer.Status {
case events.LayerStatusTypeApproved:
txstate = pb.TransactionState_TRANSACTION_STATE_MESH
case events.LayerStatusTypeConfirmed:
txstate = pb.TransactionState_TRANSACTION_STATE_PROCESSED
default:
txstate = pb.TransactionState_TRANSACTION_STATE_UNSPECIFIED
}
for _, inputTxID := range in.TransactionId {
// Since the txid coming in from the API does not have a fixed length (see
// https://github.com/spacemeshos/api/issues/130), we need to convert it from a slice to a fixed
// size array before we can convert it into a TransactionID object. We don't need to worry about
// error handling, since copy intelligently copies only what it can. If the resulting TransactionID
// is invalid, an error will be thrown below.
var arrayID [32]byte
copy(arrayID[:], inputTxID.Id[:])
txid := types.TransactionID(arrayID)
// if there is an ID corresponding to inputTxID in the block
if _, exists := blockTXIDSet[txid]; exists {
res := &pb.TransactionsStateStreamResponse{
TransactionState: &pb.TransactionState{
Id: inputTxID,
State: txstate,
},
}
if in.IncludeTransactions {
tx, err := s.conState.GetMeshTransaction(txid)
if err != nil {
ctxzap.Error(
stream.Context(),
"could not find transaction from layer",
txid.Field().Zap(),
layer.Field().Zap(),
zap.Error(err),
)
return status.Error(codes.Internal, "error retrieving tx data")
}
res.Transaction = castTransaction(&tx.Transaction)
}
if err := stream.Send(res); err != nil {
return fmt.Errorf("send stream: %w", err)
}
}
}
}
case <-stream.Context().Done():
return nil
}
// TODO: do we need an additional case here for a context to indicate
// that the service needs to shut down?
}
}
// StreamResults allows to query historical results and subscribe to live data using the same filter.
func (s TransactionService) StreamResults(
in *pb.TransactionResultsRequest,
stream pb.TransactionService_StreamResultsServer,
) error {
var (
filter transactions.ResultsFilter
sub *events.BufferedSubscription[types.TransactionWithResult]
err error
persisted types.LayerID
)
if len(in.Address) > 0 {
addr, err := types.StringToAddress(in.Address)
if err != nil {
return fmt.Errorf("failed to parse in.Address `%s`: %w", in.Address, err)
}
filter.Address = &addr
}
if len(in.Id) > 0 {
var id types.TransactionID
copy(id[:], in.Id)
filter.TID = &id
}
if in.Start > 0 {
lid := types.LayerID(in.Start)
filter.Start = &lid
}
if in.End > 0 {
if in.Watch {
return status.Error(codes.InvalidArgument, "watch stream should have an empty End argument")
}
lid := types.LayerID(in.End)
filter.End = &lid
}
if in.Watch {
sub, err = events.SubscribeMatched(resultsMatcher(filter).match)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
defer sub.Close()
if err := stream.SendHeader(metadata.MD{}); err != nil {
return status.Errorf(codes.Unavailable, "can't send header")
}
}
var ierr error
err = transactions.IterateResults(s.db, filter, func(rst *types.TransactionWithResult) bool {
if rst.Layer.After(persisted) {
persisted = rst.Layer
}
ierr = stream.Send(castResult(rst))
return ierr == nil
})
if err == nil {
err = ierr
}
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return status.Error(codes.Internal, err.Error())
}
if sub == nil {
return nil
}
for {
select {
case <-stream.Context().Done():
return nil
case <-sub.Full():
return status.Error(codes.Canceled, "buffer overflow")
case rst := <-sub.Out():
if !rst.Layer.After(persisted) {
break
}
if err := stream.Send(castResult(&rst)); err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return status.Error(codes.Internal, err.Error())
}
}
}
}
func castResult(rst *types.TransactionWithResult) *pb.TransactionResult {
casted := &pb.TransactionResult{
Tx: castTransaction(&rst.Transaction),
Status: pb.TransactionResult_Status(rst.Status),
Message: rst.Message,
GasConsumed: rst.Gas,
Fee: rst.Fee,
Block: rst.Block[:],
Layer: rst.Layer.Uint32(),
}
if len(rst.Addresses) > 0 {
casted.TouchedAddresses = make([]string, len(rst.Addresses))
for i := range rst.Addresses {
casted.TouchedAddresses[i] = rst.Addresses[i].String()
}
}
return casted
}
type resultsMatcher transactions.ResultsFilter
func (m resultsMatcher) match(rst *types.TransactionWithResult) bool {
if m.Address != nil {
found := false
for i := range rst.Addresses {
if rst.Addresses[i] == *m.Address {
found = true
break
}
}
if !found {
return false
}
}
if m.Start != nil {
if rst.Layer.Before(*m.Start) {
return false
}
}
if m.End != nil {
if rst.Layer.After(*m.End) {
return false
}
}
if m.TID != nil {
if rst.ID != *m.TID {
return false
}
}
return true
}