whisper: Fix PoW calculations to match the spec

This commit is contained in:
Guillaume Ballet 2019-03-25 13:15:54 +01:00
parent acbb8a1439
commit 21a105a38a
2 changed files with 33 additions and 5 deletions

View file

@ -130,13 +130,14 @@ func (e *Envelope) PoW() float64 {
func (e *Envelope) calculatePoW(diff uint32) { func (e *Envelope) calculatePoW(diff uint32) {
buf := make([]byte, 64) buf := make([]byte, 64)
h := crypto.Keccak256(e.rlpWithoutNonce()) rlp := e.rlpWithoutNonce()
h := crypto.Keccak256(rlp)
copy(buf[:32], h) copy(buf[:32], h)
binary.BigEndian.PutUint64(buf[56:], e.Nonce) binary.BigEndian.PutUint64(buf[56:], e.Nonce)
d := new(big.Int).SetBytes(crypto.Keccak256(buf)) powHash := new(big.Int).SetBytes(crypto.Keccak256(buf))
firstBit := math.FirstBitSet(d) leadingZeroes := 256 - powHash.BitLen()
x := gmath.Pow(2, float64(firstBit)) x := gmath.Pow(2, float64(leadingZeroes))
x /= float64(e.size()) x /= float64(len(rlp))
x /= float64(e.TTL + diff) x /= float64(e.TTL + diff)
e.pow = x e.pow = x
} }

View file

@ -25,6 +25,33 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
) )
func TestPoWCalculationsWithNoLeadingZeros(t *testing.T) {
e := Envelope{
TTL: 1,
Data: []byte{0xde, 0xad, 0xbe, 0xef},
Nonce: 100000,
}
e.calculatePoW(0)
if e.pow != 0.07692307692307693 {
t.Fatalf("invalid PoW calculation. Expected 0.07692307692307693, got %v", e.pow)
}
}
func TestPoWCalculationsWith8LeadingZeros(t *testing.T) {
e := Envelope{
TTL: 1,
Data: []byte{0xde, 0xad, 0xbe, 0xef},
Nonce: 48159,
}
e.calculatePoW(0)
if e.pow != 40329.846153846156 {
t.Fatalf("invalid PoW calculation. Expected 0.07692307692307693, got %v", e.pow)
}
}
func TestEnvelopeOpenAcceptsOnlyOneKeyTypeInFilter(t *testing.T) { func TestEnvelopeOpenAcceptsOnlyOneKeyTypeInFilter(t *testing.T) {
symKey := make([]byte, aesKeyLength) symKey := make([]byte, aesKeyLength)
mrand.Read(symKey) mrand.Read(symKey)