diff options
author | Joop Kiefte <ikojba@gmail.com> | 2021-12-12 01:32:32 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-12-12 01:40:30 +0000 |
commit | 7f41a498b057d2ab180d288f212e0adc498e203d (patch) | |
tree | 985245ef632edaee3a748946d15e848ac2f78c1a | |
parent | 4242f2656fab01837ae53ae994f1ec218030c45c (diff) |
Make messages sortable using timestamp and importance
-rw-r--r-- | message/message.go | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/message/message.go b/message/message.go index 6d8ddcd..0c5af56 100644 --- a/message/message.go +++ b/message/message.go @@ -6,7 +6,9 @@ import ( "encoding/json" "fmt" "io" + "math" "math/bits" + "sort" "sync" "time" @@ -33,6 +35,34 @@ func (m *Message) String() string { return fmt.Sprintf("Message %x sent at %s with nonce %d:\n%s", m.Hash(), time.Unix(m.Timestamp, 0).Format(time.RFC3339), m.Nonce, m.Message) } +// SortNum of a Message returns a number that can be used to sort messages by importance +// The number is calculated by taking the timestamp of the message and +// adding an importance factor of 2^(leading zeros of hash / 8) to it +// If the timestamp is in the future, return 0 instead so the message will be discarded unless there are almost no messages +func (m *Message) SortNum() int64 { + if m.Timestamp > time.Now().Unix() { + return 0 + } + importance := math.Pow(2, float64(CountLeadingZeroes(m.Hash()))/8) + return m.Timestamp + int64(importance) +} + +// MessageList returns a slice of Messages sorted by importance +// The slice is sorted by the SortNum method of the Message type +// It can be created from a Messages map by calling the Messages.Sorted method +func (m *Messages) MessageList() []*Message { + m.lock.RLock() + defer m.lock.RUnlock() + var msgs []*Message + for _, msg := range m.msgs { + msgs = append(msgs, msg) + } + sort.Slice(msgs, func(i, j int) bool { + return msgs[i].SortNum() > msgs[j].SortNum() + }) + return msgs +} + // Proof of Work: Find the nonce for a message by hashing the message and checking for at least n initial zeroes in the binary representation of the resulting hash func (msg *Message) ProofOfWork(n int) { // Create a local copy of the message and start counting |