2021-05-14 20:32:39 +00:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/hex"
|
|
|
|
"sort"
|
|
|
|
"time"
|
|
|
|
|
2021-05-19 20:54:36 +00:00
|
|
|
types2 "github.com/Secured-Finance/dione/blockchain/types"
|
2021-05-14 20:32:39 +00:00
|
|
|
|
2021-05-19 20:54:36 +00:00
|
|
|
"github.com/Secured-Finance/dione/consensus/policy"
|
2021-05-14 20:32:39 +00:00
|
|
|
|
|
|
|
"github.com/Secured-Finance/dione/cache"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
DefaultTxTTL = 10 * time.Minute
|
|
|
|
DefaultTxPrefix = "tx_"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Mempool struct {
|
2021-05-31 19:24:07 +00:00
|
|
|
cache cache.Cache
|
2021-05-14 20:32:39 +00:00
|
|
|
}
|
|
|
|
|
2021-05-31 19:24:07 +00:00
|
|
|
func NewMempool() (*Mempool, error) {
|
2021-05-14 20:32:39 +00:00
|
|
|
mp := &Mempool{
|
2021-05-31 19:24:07 +00:00
|
|
|
cache: cache.NewInMemoryCache(), // here we need to use separate cache
|
2021-05-14 20:32:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return mp, nil
|
|
|
|
}
|
|
|
|
|
2021-05-19 20:54:36 +00:00
|
|
|
func (mp *Mempool) StoreTx(tx *types2.Transaction) error {
|
2021-05-14 20:32:39 +00:00
|
|
|
hashStr := hex.EncodeToString(tx.Hash)
|
|
|
|
err := mp.cache.StoreWithTTL(DefaultTxPrefix+hashStr, tx, DefaultTxTTL)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-19 20:54:36 +00:00
|
|
|
func (mp *Mempool) GetTxsForNewBlock() []*types2.Transaction {
|
|
|
|
var txForBlock []*types2.Transaction
|
2021-05-31 19:24:07 +00:00
|
|
|
allTxs := mp.GetAllTxs()
|
2021-05-14 20:32:39 +00:00
|
|
|
sort.Slice(allTxs, func(i, j int) bool {
|
|
|
|
return allTxs[i].Timestamp.Before(allTxs[j].Timestamp)
|
|
|
|
})
|
|
|
|
|
|
|
|
for i := 0; i < policy.BlockMaxTransactionCount; i++ {
|
|
|
|
if len(allTxs) == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
tx := allTxs[0] // get oldest tx
|
|
|
|
allTxs = allTxs[1:] // pop tx
|
|
|
|
txForBlock = append(txForBlock, tx)
|
|
|
|
}
|
|
|
|
|
|
|
|
return txForBlock
|
|
|
|
}
|
|
|
|
|
2021-05-31 19:24:07 +00:00
|
|
|
func (mp *Mempool) GetAllTxs() []*types2.Transaction {
|
|
|
|
var allTxs []*types2.Transaction
|
|
|
|
|
|
|
|
for _, v := range mp.cache.Items() {
|
|
|
|
tx := v.(types2.Transaction)
|
|
|
|
allTxs = append(allTxs, &tx)
|
|
|
|
}
|
|
|
|
return allTxs
|
|
|
|
}
|
|
|
|
|
2021-05-14 20:32:39 +00:00
|
|
|
func removeItemFromStringSlice(s []string, i int) []string {
|
|
|
|
s[len(s)-1], s[i] = s[i], s[len(s)-1]
|
|
|
|
return s[:len(s)-1]
|
|
|
|
}
|