-
Notifications
You must be signed in to change notification settings - Fork 211
/
nano_tx.go
78 lines (67 loc) · 1.97 KB
/
nano_tx.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
package txs
import (
"bytes"
"time"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/hash"
"github.com/spacemeshos/go-spacemesh/log"
)
// NanoTX represents minimal info about a transaction for the conservative cache/mempool.
type NanoTX struct {
types.TxHeader
ID types.TransactionID
Received time.Time
Block types.BlockID
Layer types.LayerID
}
// NewNanoTX converts a NanoTX instance from a MeshTransaction.
func NewNanoTX(mtx *types.MeshTransaction) *NanoTX {
return &NanoTX{
ID: mtx.ID,
TxHeader: *mtx.TxHeader,
Received: mtx.Received,
Block: mtx.BlockID,
Layer: mtx.LayerID,
}
}
// MaxSpending returns the maximal amount a transaction can spend.
func (n *NanoTX) MaxSpending() uint64 {
return n.Spending()
}
func (n *NanoTX) combinedHash(blockSeed []byte) []byte {
hash := hash.New()
hash.Write(blockSeed)
hash.Write(n.ID.Bytes())
return hash.Sum(nil)
}
// Better returns true if this transaction takes priority than `other`.
// when the block seed is non-empty, this tx is being considered for a block.
// the block seed then is used to tie-break (deterministically) transactions for
// the same account/nonce.
func (n *NanoTX) Better(other *NanoTX, blockSeed []byte) bool {
if n.Principal != other.Principal ||
n.Nonce != other.Nonce {
log.Panic("invalid arguments")
}
if n.Fee() > other.Fee() {
return true
}
if n.Fee() == other.Fee() {
if len(blockSeed) > 0 {
return bytes.Compare(n.combinedHash(blockSeed), other.combinedHash(blockSeed)) < 0
}
return n.Received.Before(other.Received)
}
return false
}
// UpdateLayerMaybe updates the layer of a transaction if it's lower than the current value.
func (n *NanoTX) UpdateLayerMaybe(lid types.LayerID, bid types.BlockID) {
if n.Layer == 0 || lid.Before(n.Layer) {
n.UpdateLayer(lid, bid)
}
}
// UpdateLayer updates the layer of a transaction.
func (n *NanoTX) UpdateLayer(lid types.LayerID, bid types.BlockID) {
n.Layer = lid
n.Block = bid
}