import (
"encoding/json"
"fmt"
+ "time"
"github.com/bytom/blockchain/query"
"github.com/bytom/protocol/bc/types"
+ "sort"
)
const (
- //unconfirmedTxPrefix is txpool unconfirmed transactions prefix
- unconfirmedTxPrefix = "UTXS:"
+ //UnconfirmedTxPrefix is txpool unconfirmed transactions prefix
+ UnconfirmedTxPrefix = "UTXS:"
)
func calcUnconfirmedTxKey(formatKey string) []byte {
- return []byte(unconfirmedTxPrefix + formatKey)
+ return []byte(UnconfirmedTxPrefix + formatKey)
}
// SaveUnconfirmedTx save unconfirmed annotated transaction to the database
func (w *Wallet) SaveUnconfirmedTx(tx *types.Tx) error {
annotatedTx := &query.AnnotatedTx{
- ID: tx.ID,
- Inputs: make([]*query.AnnotatedInput, 0, len(tx.Inputs)),
- Outputs: make([]*query.AnnotatedOutput, 0, len(tx.Outputs)),
- Size: tx.SerializedSize,
+ ID: tx.ID,
+ Timestamp: uint64(time.Now().Unix()),
+ Inputs: make([]*query.AnnotatedInput, 0, len(tx.Inputs)),
+ Outputs: make([]*query.AnnotatedOutput, 0, len(tx.Outputs)),
+ Size: tx.SerializedSize,
}
for i := range tx.Inputs {
return annotatedTx, nil
}
+// SortByTimestamp implements sort.Interface for AnnotatedTx slices
+type SortByTimestamp []*query.AnnotatedTx
+
+func (a SortByTimestamp) Len() int { return len(a) }
+func (a SortByTimestamp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a SortByTimestamp) Less(i, j int) bool { return a[i].Timestamp > a[j].Timestamp }
+
// GetUnconfirmedTxs get account unconfirmed transactions, filter transactions by accountID when accountID is not empty
func (w *Wallet) GetUnconfirmedTxs(accountID string) ([]*query.AnnotatedTx, error) {
annotatedTxs := []*query.AnnotatedTx{}
- txIter := w.DB.IteratorPrefix([]byte(unconfirmedTxPrefix))
+ txIter := w.DB.IteratorPrefix([]byte(UnconfirmedTxPrefix))
defer txIter.Release()
for txIter.Next() {
annotatedTx := &query.AnnotatedTx{}
}
if accountID == "" || findTransactionsByAccount(annotatedTx, accountID) {
- annotateTxsAsset(w, annotatedTxs)
- annotatedTxs = append(annotatedTxs, annotatedTx)
+ annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
+ annotatedTxs = append([]*query.AnnotatedTx{annotatedTx}, annotatedTxs...)
}
}
+ // sort SortByTimestamp by timestamp
+ sort.Sort(SortByTimestamp(annotatedTxs))
return annotatedTxs, nil
}