From 563c0e494e7181b0beacb406a91b8541e5cb9cbb Mon Sep 17 00:00:00 2001 From: Jakub Sztandera Date: Mon, 28 Oct 2019 20:01:10 +0100 Subject: [PATCH] Use div-free EC power selection function License: MIT Signed-off-by: Jakub Sztandera --- chain/types/blockheader.go | 21 +++++++++++++-------- go.mod | 1 + 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/chain/types/blockheader.go b/chain/types/blockheader.go index 6109df28f..6db0a720c 100644 --- a/chain/types/blockheader.go +++ b/chain/types/blockheader.go @@ -3,11 +3,11 @@ package types import ( "bytes" "context" - "crypto/sha256" "math/big" block "github.com/ipfs/go-block-format" "github.com/ipfs/go-cid" + "github.com/minio/sha256-simd" "github.com/multiformats/go-multihash" "go.opencensus.io/trace" xerrors "golang.org/x/xerrors" @@ -166,19 +166,24 @@ func PowerCmp(eproof ElectionProof, mpow, totpow BigInt) bool { /* Need to check that - h(vrfout) / 2^256 < minerPower / totalPower + h(vrfout) / max(h) * e < minerPower / totalPower + max(h) == 2^256-1 + which in terms of integer math means: + h(vrfout) * totalPower * e < minerPower * (2^256-1) */ h := sha256.Sum256(eproof) - // 2^256 - rden := BigInt{big.NewInt(0).Exp(big.NewInt(2), big.NewInt(256), nil)} + lhs := BigFromBytes(h[:]).Int + lhs = lhs.Mul(lhs, blocksPerEpoch.Int) + lhs = lhs.Mul(lhs, totpow.Int) - top := BigMul(BigMul(rden, mpow), blocksPerEpoch) - out := BigDiv(top, totpow) + // rhs = minerPower * 2^256 - minerPower + // rhs = minerPower << 256 - minerPower + rhs := new(big.Int).Lsh(mpow.Int, 256) + rhs = rhs.Sub(rhs, mpow.Int) - hp := BigFromBytes(h[:]) - return hp.LessThan(out) + return lhs.Cmp(rhs) == -1 } func (t *Ticket) Equals(ot *Ticket) bool { diff --git a/go.mod b/go.mod index 343315e1c..b8eec445f 100644 --- a/go.mod +++ b/go.mod @@ -61,6 +61,7 @@ require ( github.com/mattn/go-runewidth v0.0.4 // indirect github.com/miekg/dns v1.1.16 // indirect github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 + github.com/minio/sha256-simd v0.1.0 github.com/mitchellh/go-homedir v1.1.0 github.com/multiformats/go-base32 v0.0.3 github.com/multiformats/go-multiaddr v0.0.4