Proper hash ordering, from consensus

This commit is contained in:
DataHoarder 2022-11-07 08:37:39 +01:00
parent 23bf5a9f0f
commit c0921997bc
Signed by: DataHoarder
SSH key fingerprint: SHA256:OLTRf6Fl87G52SiR7sWLGNzlJt4WOX+tfI2yxo0z7xk
2 changed files with 42 additions and 1 deletions

View file

@ -329,7 +329,7 @@ func (c *SideChain) verifyBlock(block *PoolBlock) (verification error, invalid e
if i == 0 {
continue
}
if bytes.Compare(block.Side.Uncles[i-1][:], uncleId[:]) < 0 {
if block.Side.Uncles[i-1].Compare(uncleId) != -1 {
return nil, errors.New("invalid uncle order")
}
}

View file

@ -5,6 +5,8 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"runtime"
"unsafe"
)
const HashSize = 32
@ -38,6 +40,45 @@ func HashFromBytes(buf []byte) (h Hash) {
return
}
// Compare consensus way of comparison
func (h Hash) Compare(other Hash) int {
//golang might free other otherwise
defer runtime.KeepAlive(other)
defer runtime.KeepAlive(h)
a := unsafe.Slice((*uint64)(unsafe.Pointer(&h)), len(h)/int(unsafe.Sizeof(uint64(0))))
b := unsafe.Slice((*uint64)(unsafe.Pointer(&other)), len(other)/int(unsafe.Sizeof(uint64(0))))
if a[3] < b[3] {
return -1
}
if a[3] > b[3] {
return 1
}
if a[2] < b[2] {
return -1
}
if a[2] > b[2] {
return 1
}
if a[1] < b[1] {
return -1
}
if a[1] > b[1] {
return 1
}
if a[0] < b[0] {
return -1
}
if a[0] > b[0] {
return 1
}
return 0
}
func (h Hash) Equals(o Hash) bool {
return bytes.Compare(h[:], o[:]) == 0
}