-
Notifications
You must be signed in to change notification settings - Fork 178
/
transactions.go
88 lines (75 loc) · 2.42 KB
/
transactions.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
package herocache
import (
"fmt"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module"
herocache "github.com/onflow/flow-go/module/mempool/herocache/backdata"
"github.com/onflow/flow-go/module/mempool/herocache/backdata/heropool"
"github.com/onflow/flow-go/module/mempool/stdmap"
)
type Transactions struct {
c *stdmap.Backend
}
// NewTransactions implements a transactions mempool based on hero cache.
func NewTransactions(limit uint32, logger zerolog.Logger, collector module.HeroCacheMetrics) *Transactions {
t := &Transactions{
c: stdmap.NewBackend(
stdmap.WithBackData(
herocache.NewCache(limit,
herocache.DefaultOversizeFactor,
heropool.LRUEjection,
logger.With().Str("mempool", "transactions").Logger(),
collector))),
}
return t
}
// Has checks whether the transaction with the given hash is currently in
// the memory pool.
func (t Transactions) Has(id flow.Identifier) bool {
return t.c.Has(id)
}
// Add adds a transaction to the mempool.
func (t *Transactions) Add(tx *flow.TransactionBody) bool {
// Warning! reference pointer must be dereferenced before adding to HeroCache.
// This is crucial for its heap object optimizations.
return t.c.Add(*tx)
}
// ByID returns the transaction with the given ID from the mempool.
func (t Transactions) ByID(txID flow.Identifier) (*flow.TransactionBody, bool) {
entity, exists := t.c.ByID(txID)
if !exists {
return nil, false
}
tx, ok := entity.(flow.TransactionBody)
if !ok {
panic(fmt.Sprintf("invalid entity in transaction pool (%T)", entity))
}
return &tx, true
}
// All returns all transactions from the mempool. Since it is using the HeroCache, All guarantees returning
// all transactions in the same order as they are added.
func (t Transactions) All() []*flow.TransactionBody {
entities := t.c.All()
txs := make([]*flow.TransactionBody, 0, len(entities))
for _, entity := range entities {
tx, ok := entity.(flow.TransactionBody)
if !ok {
panic(fmt.Sprintf("invalid entity in transaction pool (%T)", entity))
}
txs = append(txs, &tx)
}
return txs
}
// Clear removes all transactions stored in this mempool.
func (t *Transactions) Clear() {
t.c.Clear()
}
// Size returns total number of stored transactions.
func (t Transactions) Size() uint {
return t.c.Size()
}
// Remove removes transaction from mempool.
func (t *Transactions) Remove(id flow.Identifier) bool {
return t.c.Remove(id)
}