aboutsummaryrefslogtreecommitdiffstats
path: root/core
diff options
context:
space:
mode:
authorPéter Szilágyi <peterke@gmail.com>2017-08-10 21:39:43 +0800
committerPéter Szilágyi <peterke@gmail.com>2017-08-14 20:27:44 +0800
commit6131dd55c5cb6f964a1b8e8d51400f10d545a92e (patch)
tree3ac0b6667e5e2afbad8f7f5a528bc78f2517e78d /core
parent7bbdf3e2687ea293b68a7f73c039cbde411217fa (diff)
downloadgo-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.tar
go-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.tar.gz
go-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.tar.bz2
go-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.tar.lz
go-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.tar.xz
go-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.tar.zst
go-tangerine-6131dd55c5cb6f964a1b8e8d51400f10d545a92e.zip
core/vm: polish precompile contract code, add tests and benches
* Update modexp gas calculation to new version * Fix modexp modulo 0 special case to return zero
Diffstat (limited to 'core')
-rw-r--r--core/vm/contracts.go349
-rw-r--r--core/vm/contracts_test.go101
-rw-r--r--core/vm/evm.go15
-rw-r--r--core/vm/instructions_test.go86
4 files changed, 355 insertions, 196 deletions
diff --git a/core/vm/contracts.go b/core/vm/contracts.go
index 407f198f0..c59779dac 100644
--- a/core/vm/contracts.go
+++ b/core/vm/contracts.go
@@ -29,9 +29,7 @@ import (
"golang.org/x/crypto/ripemd160"
)
-var errBadPrecompileInput = errors.New("bad pre compile input")
-
-// Precompiled contract is the basic interface for native Go contracts. The implementation
+// PrecompiledContract is the basic interface for native Go contracts. The implementation
// requires a deterministic gas count based on the input size of the Run method of the
// contract.
type PrecompiledContract interface {
@@ -39,61 +37,61 @@ type PrecompiledContract interface {
Run(input []byte) ([]byte, error) // Run runs the precompiled contract
}
-// PrecompiledContracts contains the default set of ethereum contracts
-var PrecompiledContracts = map[common.Address]PrecompiledContract{
+// PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
+// contracts used in the Frontier and Homestead releases.
+var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
common.BytesToAddress([]byte{1}): &ecrecover{},
common.BytesToAddress([]byte{2}): &sha256hash{},
common.BytesToAddress([]byte{3}): &ripemd160hash{},
common.BytesToAddress([]byte{4}): &dataCopy{},
}
-// PrecompiledContractsMetropolis contains the default set of ethereum contracts
-// for metropolis hardfork
+// PrecompiledContractsMetropolis contains the default set of pre-compiled Ethereum
+// contracts used in the Metropolis release.
var PrecompiledContractsMetropolis = map[common.Address]PrecompiledContract{
common.BytesToAddress([]byte{1}): &ecrecover{},
common.BytesToAddress([]byte{2}): &sha256hash{},
common.BytesToAddress([]byte{3}): &ripemd160hash{},
common.BytesToAddress([]byte{4}): &dataCopy{},
- common.BytesToAddress([]byte{5}): &bigModexp{},
+ common.BytesToAddress([]byte{5}): &bigModExp{},
common.BytesToAddress([]byte{6}): &bn256Add{},
common.BytesToAddress([]byte{7}): &bn256ScalarMul{},
- common.BytesToAddress([]byte{8}): &pairing{},
+ common.BytesToAddress([]byte{8}): &bn256Pairing{},
}
-// RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
+// RunPrecompiledContract runs and evaluates the output of a precompiled contract.
func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
gas := p.RequiredGas(input)
if contract.UseGas(gas) {
return p.Run(input)
- } else {
- return nil, ErrOutOfGas
}
+ return nil, ErrOutOfGas
}
-// ECRECOVER implemented as a native contract
+// ECRECOVER implemented as a native contract.
type ecrecover struct{}
func (c *ecrecover) RequiredGas(input []byte) uint64 {
return params.EcrecoverGas
}
-func (c *ecrecover) Run(in []byte) ([]byte, error) {
+func (c *ecrecover) Run(input []byte) ([]byte, error) {
const ecRecoverInputLength = 128
- in = common.RightPadBytes(in, ecRecoverInputLength)
- // "in" is (hash, v, r, s), each 32 bytes
+ input = common.RightPadBytes(input, ecRecoverInputLength)
+ // "input" is (hash, v, r, s), each 32 bytes
// but for ecrecover we want (r, s, v)
- r := new(big.Int).SetBytes(in[64:96])
- s := new(big.Int).SetBytes(in[96:128])
- v := in[63] - 27
+ r := new(big.Int).SetBytes(input[64:96])
+ s := new(big.Int).SetBytes(input[96:128])
+ v := input[63] - 27
- // tighter sig s values in homestead only apply to tx sigs
- if !allZero(in[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
+ // tighter sig s values input homestead only apply to tx sigs
+ if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
return nil, nil
}
// v needs to be at the end for libsecp256k1
- pubKey, err := crypto.Ecrecover(in[:32], append(in[64:128], v))
+ pubKey, err := crypto.Ecrecover(input[:32], append(input[64:128], v))
// make sure the public key is a valid one
if err != nil {
return nil, nil
@@ -103,7 +101,7 @@ func (c *ecrecover) Run(in []byte) ([]byte, error) {
return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
}
-// SHA256 implemented as a native contract
+// SHA256 implemented as a native contract.
type sha256hash struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
@@ -111,14 +109,14 @@ type sha256hash struct{}
// This method does not require any overflow checking as the input size gas costs
// required for anything significant is so high it's impossible to pay for.
func (c *sha256hash) RequiredGas(input []byte) uint64 {
- return uint64(len(input)+31)/32*params.Sha256WordGas + params.Sha256Gas
+ return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
}
-func (c *sha256hash) Run(in []byte) ([]byte, error) {
- h := sha256.Sum256(in)
+func (c *sha256hash) Run(input []byte) ([]byte, error) {
+ h := sha256.Sum256(input)
return h[:], nil
}
-// RIPMED160 implemented as a native contract
+// RIPMED160 implemented as a native contract.
type ripemd160hash struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
@@ -126,15 +124,15 @@ type ripemd160hash struct{}
// This method does not require any overflow checking as the input size gas costs
// required for anything significant is so high it's impossible to pay for.
func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
- return uint64(len(input)+31)/32*params.Ripemd160WordGas + params.Ripemd160Gas
+ return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
}
-func (c *ripemd160hash) Run(in []byte) ([]byte, error) {
+func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
ripemd := ripemd160.New()
- ripemd.Write(in)
+ ripemd.Write(input)
return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
}
-// data copy implemented as a native contract
+// data copy implemented as a native contract.
type dataCopy struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
@@ -142,195 +140,232 @@ type dataCopy struct{}
// This method does not require any overflow checking as the input size gas costs
// required for anything significant is so high it's impossible to pay for.
func (c *dataCopy) RequiredGas(input []byte) uint64 {
- return uint64(len(input)+31)/32*params.IdentityWordGas + params.IdentityGas
+ return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
}
func (c *dataCopy) Run(in []byte) ([]byte, error) {
return in, nil
}
-// bigModexp implements a native big integer exponential modular operation.
-type bigModexp struct{}
+// bigModExp implements a native big integer exponential modular operation.
+type bigModExp struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
-//
-// This method does not require any overflow checking as the input size gas costs
-// required for anything significant is so high it's impossible to pay for.
-func (c *bigModexp) RequiredGas(input []byte) uint64 {
- // TODO reword required gas to have error reporting and convert arithmetic
- // to uint64.
- if len(input) < 3*32 {
- input = append(input, make([]byte, 3*32-len(input))...)
- }
+func (c *bigModExp) RequiredGas(input []byte) uint64 {
+ // Pad the input with zeroes to the minimum size to read the field lengths
+ input = common.RightPadBytes(input, 96)
+
var (
- baseLen = new(big.Int).SetBytes(input[:31])
- expLen = math.BigMax(new(big.Int).SetBytes(input[32:64]), big.NewInt(1))
- modLen = new(big.Int).SetBytes(input[65:97])
+ baseLen = new(big.Int).SetBytes(input[:32])
+ expLen = new(big.Int).SetBytes(input[32:64])
+ modLen = new(big.Int).SetBytes(input[64:96])
)
- x := new(big.Int).Set(math.BigMax(baseLen, modLen))
- x.Mul(x, x)
- x.Mul(x, expLen)
- x.Div(x, new(big.Int).SetUint64(params.QuadCoeffDiv))
+ input = input[96:]
- return x.Uint64()
-}
+ // Retrieve the head 32 bytes of exp for the adjusted exponent length
+ var expHead *big.Int
+ if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
+ expHead = new(big.Int)
+ } else {
+ offset := int(baseLen.Uint64())
-func (c *bigModexp) Run(input []byte) ([]byte, error) {
- if len(input) < 3*32 {
- input = append(input, make([]byte, 3*32-len(input))...)
+ input = common.RightPadBytes(input, offset+32)
+ if expLen.Cmp(big.NewInt(32)) > 0 {
+ expHead = new(big.Int).SetBytes(input[offset : offset+32])
+ } else {
+ expHead = new(big.Int).SetBytes(input[offset : offset+int(expLen.Uint64())])
+ }
}
- // why 32-byte? These values won't fit anyway
+ // Calculate the adjusted exponent length
+ var msb int
+ if bitlen := expHead.BitLen(); bitlen > 0 {
+ msb = bitlen - 1
+ }
+ adjExpLen := new(big.Int)
+ if expLen.Cmp(big.NewInt(32)) > 0 {
+ adjExpLen.Sub(expLen, big.NewInt(32))
+ adjExpLen.Mul(big.NewInt(8), adjExpLen)
+ }
+ adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
+
+ // Calculate the gas cost of the operation
+ gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
+ switch {
+ case gas.Cmp(big.NewInt(64)) <= 0:
+ gas.Mul(gas, gas)
+ case gas.Cmp(big.NewInt(1024)) <= 0:
+ gas = new(big.Int).Add(
+ new(big.Int).Div(new(big.Int).Mul(gas, gas), big.NewInt(4)),
+ new(big.Int).Sub(new(big.Int).Mul(big.NewInt(96), gas), big.NewInt(3072)),
+ )
+ default:
+ gas = new(big.Int).Add(
+ new(big.Int).Div(new(big.Int).Mul(gas, gas), big.NewInt(16)),
+ new(big.Int).Sub(new(big.Int).Mul(big.NewInt(480), gas), big.NewInt(199680)),
+ )
+ }
+ gas.Mul(gas, math.BigMax(adjExpLen, big.NewInt(1)))
+ gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
+
+ if gas.BitLen() > 64 {
+ return math.MaxUint64
+ }
+ return gas.Uint64()
+}
+
+func (c *bigModExp) Run(input []byte) ([]byte, error) {
+ // Pad the input with zeroes to the minimum size to read the field lengths
+ input = common.RightPadBytes(input, 96)
+
var (
baseLen = new(big.Int).SetBytes(input[:32]).Uint64()
expLen = new(big.Int).SetBytes(input[32:64]).Uint64()
modLen = new(big.Int).SetBytes(input[64:96]).Uint64()
)
-
input = input[96:]
- if uint64(len(input)) < baseLen {
- input = append(input, make([]byte, baseLen-uint64(len(input)))...)
- }
- base := new(big.Int).SetBytes(input[:baseLen])
- input = input[baseLen:]
- if uint64(len(input)) < expLen {
- input = append(input, make([]byte, expLen-uint64(len(input)))...)
- }
- exp := new(big.Int).SetBytes(input[:expLen])
+ // Pad the input with zeroes to the minimum size to read the field contents
+ input = common.RightPadBytes(input, int(baseLen+expLen+modLen))
- input = input[expLen:]
- if uint64(len(input)) < modLen {
- input = append(input, make([]byte, modLen-uint64(len(input)))...)
+ var (
+ base = new(big.Int).SetBytes(input[:baseLen])
+ exp = new(big.Int).SetBytes(input[baseLen : baseLen+expLen])
+ mod = new(big.Int).SetBytes(input[baseLen+expLen : baseLen+expLen+modLen])
+ )
+ if mod.BitLen() == 0 {
+ // Modulo 0 is undefined, return zero
+ return common.LeftPadBytes([]byte{}, int(modLen)), nil
}
- mod := new(big.Int).SetBytes(input[:modLen])
-
- return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), len(input[:modLen])), nil
+ return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
}
-type bn256Add struct{}
-
-// RequiredGas returns the gas required to execute the pre-compiled contract.
-//
-// This method does not require any overflow checking as the input size gas costs
-// required for anything significant is so high it's impossible to pay for.
-func (c *bn256Add) RequiredGas(input []byte) uint64 {
- return 0 // TODO
-}
+var (
+ // errNotOnCurve is returned if a point being unmarshalled as a bn256 elliptic
+ // curve point is not on the curve.
+ errNotOnCurve = errors.New("point not on elliptic curve")
-func (c *bn256Add) Run(in []byte) ([]byte, error) {
- in = common.RightPadBytes(in, 128)
+ // errInvalidCurvePoint is returned if a point being unmarshalled as a bn256
+ // elliptic curve point is invalid.
+ errInvalidCurvePoint = errors.New("invalid elliptic curve point")
+)
- x, onCurve := new(bn256.G1).Unmarshal(in[:64])
+// newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
+// returning it, or an error if the point is invalid.
+func newCurvePoint(blob []byte) (*bn256.G1, error) {
+ p, onCurve := new(bn256.G1).Unmarshal(blob)
if !onCurve {
return nil, errNotOnCurve
}
- gx, gy, _, _ := x.CurvePoints()
+ gx, gy, _, _ := p.CurvePoints()
if gx.Cmp(bn256.P) >= 0 || gy.Cmp(bn256.P) >= 0 {
return nil, errInvalidCurvePoint
}
+ return p, nil
+}
- y, onCurve := new(bn256.G1).Unmarshal(in[64:128])
+// newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
+// returning it, or an error if the point is invalid.
+func newTwistPoint(blob []byte) (*bn256.G2, error) {
+ p, onCurve := new(bn256.G2).Unmarshal(blob)
if !onCurve {
return nil, errNotOnCurve
}
- gx, gy, _, _ = y.CurvePoints()
- if gx.Cmp(bn256.P) >= 0 || gy.Cmp(bn256.P) >= 0 {
+ x2, y2, _, _ := p.CurvePoints()
+ if x2.Real().Cmp(bn256.P) >= 0 || x2.Imag().Cmp(bn256.P) >= 0 ||
+ y2.Real().Cmp(bn256.P) >= 0 || y2.Imag().Cmp(bn256.P) >= 0 {
return nil, errInvalidCurvePoint
}
- x.Add(x, y)
-
- return x.Marshal(), nil
+ return p, nil
}
-type bn256ScalarMul struct{}
+// bn256Add implements a native elliptic curve point addition.
+type bn256Add struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
-//
-// This method does not require any overflow checking as the input size gas costs
-// required for anything significant is so high it's impossible to pay for.
-func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
- return 0 // TODO
+func (c *bn256Add) RequiredGas(input []byte) uint64 {
+ return params.Bn256AddGas
}
-func (c *bn256ScalarMul) Run(in []byte) ([]byte, error) {
- in = common.RightPadBytes(in, 96)
+func (c *bn256Add) Run(input []byte) ([]byte, error) {
+ // Ensure we have enough data to operate on
+ input = common.RightPadBytes(input, 128)
- g1, onCurve := new(bn256.G1).Unmarshal(in[:64])
- if !onCurve {
- return nil, errNotOnCurve
+ x, err := newCurvePoint(input[:64])
+ if err != nil {
+ return nil, err
}
- x, y, _, _ := g1.CurvePoints()
- if x.Cmp(bn256.P) >= 0 || y.Cmp(bn256.P) >= 0 {
- return nil, errInvalidCurvePoint
+ y, err := newCurvePoint(input[64:128])
+ if err != nil {
+ return nil, err
}
- g1.ScalarMult(g1, new(big.Int).SetBytes(in[64:96]))
-
- return g1.Marshal(), nil
+ x.Add(x, y)
+ return x.Marshal(), nil
}
-// pairing implements a pairing pre-compile for the bn256 curve
-type pairing struct{}
+// bn256ScalarMul implements a native elliptic curve scalar multiplication.
+type bn256ScalarMul struct{}
// RequiredGas returns the gas required to execute the pre-compiled contract.
-//
-// This method does not require any overflow checking as the input size gas costs
-// required for anything significant is so high it's impossible to pay for.
-func (c *pairing) RequiredGas(input []byte) uint64 {
- //return 0 // TODO
- k := (len(input) + 191) / pairSize
- return uint64(60000*k + 40000)
+func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
+ return params.Bn256ScalarMulGas
}
-const pairSize = 192
+func (c *bn256ScalarMul) Run(input []byte) ([]byte, error) {
+ // Ensure we have enough data to operate on
+ input = common.RightPadBytes(input, 96)
+
+ p, err := newCurvePoint(input[:64])
+ if err != nil {
+ return nil, err
+ }
+ p.ScalarMult(p, new(big.Int).SetBytes(input[64:96]))
+ return p.Marshal(), nil
+}
var (
- true32Byte = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
- fals32Byte = make([]byte, 32)
- errNotOnCurve = errors.New("point not on elliptic curve")
- errInvalidCurvePoint = errors.New("invalid elliptic curve point")
+ // true32Byte is returned if the bn256 pairing check succeeds.
+ true32Byte = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
+
+ // false32Byte is returned if the bn256 pairing check fails.
+ false32Byte = make([]byte, 32)
+
+ // errBadPairingInput is returned if the bn256 pairing input is invalid.
+ errBadPairingInput = errors.New("bad elliptic curve pairing size")
)
-func (c *pairing) Run(in []byte) ([]byte, error) {
- if len(in) == 0 {
- return true32Byte, nil
- }
+// bn256Pairing implements a pairing pre-compile for the bn256 curve
+type bn256Pairing struct{}
- if len(in)%pairSize > 0 {
- return nil, errBadPrecompileInput
- }
+// RequiredGas returns the gas required to execute the pre-compiled contract.
+func (c *bn256Pairing) RequiredGas(input []byte) uint64 {
+ return params.Bn256PairingBaseGas + uint64(len(input)/192)*params.Bn256PairingPerPointGas
+}
+func (c *bn256Pairing) Run(input []byte) ([]byte, error) {
+ // Handle some corner cases cheaply
+ if len(input)%192 > 0 {
+ return nil, errBadPairingInput
+ }
+ // Convert the input into a set of coordinates
var (
- g1s []*bn256.G1
- g2s []*bn256.G2
+ cs []*bn256.G1
+ ts []*bn256.G2
)
- for i := 0; i < len(in); i += pairSize {
- g1, onCurve := new(bn256.G1).Unmarshal(in[i : i+64])
- if !onCurve {
- return nil, errNotOnCurve
- }
-
- x, y, _, _ := g1.CurvePoints()
- if x.Cmp(bn256.P) >= 0 || y.Cmp(bn256.P) >= 0 {
- return nil, errInvalidCurvePoint
+ for i := 0; i < len(input); i += 192 {
+ c, err := newCurvePoint(input[i : i+64])
+ if err != nil {
+ return nil, err
}
-
- g2, onCurve := new(bn256.G2).Unmarshal(in[i+64 : i+192])
- if !onCurve {
- return nil, errNotOnCurve
- }
- x2, y2, _, _ := g2.CurvePoints()
- if x2.Real().Cmp(bn256.P) >= 0 || x2.Imag().Cmp(bn256.P) >= 0 ||
- y2.Real().Cmp(bn256.P) >= 0 || y2.Imag().Cmp(bn256.P) >= 0 {
- return nil, errInvalidCurvePoint
+ t, err := newTwistPoint(input[i+64 : i+192])
+ if err != nil {
+ return nil, err
}
-
- g1s = append(g1s, g1)
- g2s = append(g2s, g2)
+ cs = append(cs, c)
+ ts = append(ts, t)
}
-
- isOne := bn256.PairingCheck(g1s, g2s)
- if isOne {
+ // Execute the pairing checks and return the results
+ ok := bn256.PairingCheck(cs, ts)
+ if ok {
return true32Byte, nil
}
-
- return fals32Byte, nil
+ return false32Byte, nil
}
diff --git a/core/vm/contracts_test.go b/core/vm/contracts_test.go
index 2b4070ede..d04957161 100644
--- a/core/vm/contracts_test.go
+++ b/core/vm/contracts_test.go
@@ -1,17 +1,100 @@
package vm
import (
+ "bytes"
+ "math"
"testing"
"github.com/ethereum/go-ethereum/common"
)
-const input = ""
+// Tests the sample inputs from the ModExp EIP 198.
+func TestPrecompiledModExp(t *testing.T) {
+ bigModExp := &bigModExp{}
-func TestPairing(t *testing.T) {
- pairing := &pairing{}
+ for i, tt := range []struct {
+ input string
+ gas uint64
+ output string
+ }{
+ {"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002003fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2efffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", 2611, "0000000000000000000000000000000000000000000000000000000000000001"},
+ {"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2efffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", 2611, "0000000000000000000000000000000000000000000000000000000000000000"},
+ {"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", math.MaxUint64, ""},
+ {"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002003ffff800000000000000000000000000000000000000000000000000000000000000007", 153, "3b01b01ac41f2d6e917c6d6a221ce793802469026d9ab7578fa2e79e4da6aaab"},
+ {"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000002003ffff80", 153, "3b01b01ac41f2d6e917c6d6a221ce793802469026d9ab7578fa2e79e4da6aaab"},
+ } {
+ gas := bigModExp.RequiredGas(common.FromHex(tt.input))
+ if gas != tt.gas {
+ t.Errorf("test %d: required gas mismatch: have %v, want %v", i, gas, tt.gas)
+ continue
+ }
+ if gas == math.MaxUint64 {
+ continue // Out of gas
+ }
+ out, err := bigModExp.Run(common.FromHex(tt.input))
+ if err != nil {
+ t.Errorf("test %d: contract execution failed: %v", i, err)
+ continue
+ }
+ if !bytes.Equal(out, common.FromHex(tt.output)) {
+ t.Errorf("test %d: contract output mismatch: have %x, want %v", i, out, tt.output)
+ }
+ }
+}
+
+// Tests the sample inputs from the elliptic curve addition EIP 213.
+func TestPrecompiledBn256Add(t *testing.T) {
+ bn256Add := &bn256Add{}
+
+ for i, tt := range []struct {
+ input string
+ failure error
+ output string
+ }{
+ {"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", nil, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"},
+ {"", nil, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"},
+ {"1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", errNotOnCurve, ""},
+ } {
+ out, err := bn256Add.Run(common.FromHex(tt.input))
+ if err != tt.failure {
+ t.Errorf("test %d: contract execution failure mismatch: have %v, want %v", i, err, tt.failure)
+ continue
+ }
+ if !bytes.Equal(out, common.FromHex(tt.output)) {
+ t.Errorf("test %d: contract output mismatch: have %x, want %v", i, out, tt.output)
+ }
+ }
+}
+
+// Tests the sample inputs from the elliptic curve scalar multiplication EIP 213.
+func TestPrecompiledBn256ScalarMul(t *testing.T) {
+ bn256ScalarMul := &bn256ScalarMul{}
+
+ for i, tt := range []struct {
+ input string
+ failure error
+ output string
+ }{
+ {"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000", nil, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"},
+ {"", nil, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"},
+ {"111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110f00000000000000000000000000000000000000000000000000000000000000", errNotOnCurve, ""},
+ } {
+ out, err := bn256ScalarMul.Run(common.FromHex(tt.input))
+ if err != tt.failure {
+ t.Errorf("test %d: contract execution failure mismatch: have %v, want %v", i, err, tt.failure)
+ continue
+ }
+ if !bytes.Equal(out, common.FromHex(tt.output)) {
+ t.Errorf("test %d: contract output mismatch: have %x, want %v", i, out, tt.output)
+ }
+ }
+}
- for i, test := range []struct {
+// Tests the sample inputs from the elliptic curve pairing check EIP 197.
+func TestPrecompiledBn256Pairing(t *testing.T) {
+ bn256Pairing := &bn256Pairing{}
+
+ for i, tt := range []struct {
input string
valid int
}{
@@ -22,14 +105,12 @@ func TestPairing(t *testing.T) {
{"20a754d2071d4d53903e3b31a7e98ad6882d58aec240ef981fdf0a9d22c5926a29c853fcea789887315916bbeb89ca37edb355b4f980c9a12a94f30deeed30211213d2149b006137fcfb23036606f848d638d576a120ca981b5b1a5f9300b3ee2276cf730cf493cd95d64677bbb75fc42db72513a4c1e387b476d056f80aa75f21ee6226d31426322afcda621464d0611d226783262e21bb3bc86b537e986237096df1f82dff337dd5972e32a8ad43e28a78a96a823ef1cd4debe12b6552ea5f1abb4a25eb9379ae96c84fff9f0540abcfc0a0d11aeda02d4f37e4baf74cb0c11073b3ff2cdbb38755f8691ea59e9606696b3ff278acfc098fa8226470d03869217cee0a9ad79a4493b5253e2e4e3a39fc2df38419f230d341f60cb064a0ac290a3d76f140db8418ba512272381446eb73958670f00cf46f1d9e64cba057b53c26f64a8ec70387a13e41430ed3ee4a7db2059cc5fc13c067194bcc0cb49a98552fd72bd9edb657346127da132e5b82ab908f5816c826acb499e22f2412d1a2d70f25929bcb43d5a57391564615c9e70a992b10eafa4db109709649cf48c50dd2198a1f162a73261f112401aa2db79c7dab1533c9935c77290a6ce3b191f2318d198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa", 1},
{"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f593034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf704bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a416782bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c103188585e2364128fe25c70558f1560f4f9350baf3959e603cc91486e110936198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa", 0},
} {
- r, err := pairing.Run(common.FromHex(test.input))
+ out, err := bn256Pairing.Run(common.FromHex(tt.input))
if err != nil {
- t.Error(i, ":", err)
+ t.Errorf("test %d: contrac execution failed: %v", i, err)
}
-
- if int(r[31]) != test.valid {
- t.Error(i, "expected", test.valid, "but was", r[31])
+ if int(out[31]) != tt.valid {
+ t.Errorf("test %d: contract output mismatch: have %v, want %v", i, out[31], tt.valid)
}
}
-
}
diff --git a/core/vm/evm.go b/core/vm/evm.go
index 20eaaccb4..b8af9bd15 100644
--- a/core/vm/evm.go
+++ b/core/vm/evm.go
@@ -36,16 +36,14 @@ type (
// run runs the given contract and takes care of running precompiles with a fallback to the byte code interpreter.
func run(evm *EVM, snapshot int, contract *Contract, input []byte) ([]byte, error) {
if contract.CodeAddr != nil {
- precompiledContracts := PrecompiledContracts
+ precompiles := PrecompiledContractsHomestead
if evm.ChainConfig().IsMetropolis(evm.BlockNumber) {
- precompiledContracts = PrecompiledContractsMetropolis
+ precompiles = PrecompiledContractsMetropolis
}
-
- if p := precompiledContracts[*contract.CodeAddr]; p != nil {
+ if p := precompiles[*contract.CodeAddr]; p != nil {
return RunPrecompiledContract(p, input, contract)
}
}
-
return evm.interpreter.Run(snapshot, contract, input)
}
@@ -147,10 +145,13 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
snapshot = evm.StateDB.Snapshot()
)
if !evm.StateDB.Exist(addr) {
- if PrecompiledContracts[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
+ precompiles := PrecompiledContractsHomestead
+ if evm.ChainConfig().IsMetropolis(evm.BlockNumber) {
+ precompiles = PrecompiledContractsMetropolis
+ }
+ if precompiles[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
return nil, gas, nil
}
-
evm.StateDB.CreateAccount(addr)
}
evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
diff --git a/core/vm/instructions_test.go b/core/vm/instructions_test.go
index 03c42c561..13e411d12 100644
--- a/core/vm/instructions_test.go
+++ b/core/vm/instructions_test.go
@@ -69,7 +69,7 @@ func precompiledBenchmark(addr, input, expected string, gas uint64, bench *testi
contract := NewContract(AccountRef(common.HexToAddress("1337")),
nil, new(big.Int), gas)
- p := PrecompiledContracts[common.HexToAddress(addr)]
+ p := PrecompiledContractsMetropolis[common.HexToAddress(addr)]
in := common.Hex2Bytes(input)
var (
res []byte
@@ -94,7 +94,7 @@ func precompiledBenchmark(addr, input, expected string, gas uint64, bench *testi
}
}
-func BenchmarkPrecompiledEcdsa(bench *testing.B) {
+func BenchmarkPrecompiledECDSA(bench *testing.B) {
var (
addr = "01"
inp = "38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9ed98873e000000000000000000000000000000000000000000000000000000000000001b38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9ed98873e789d1dd423d25f0772d2748d60f7e4b81bb14d086eba8e8e8efb6dcff8a4ae02"
@@ -103,6 +103,7 @@ func BenchmarkPrecompiledEcdsa(bench *testing.B) {
)
precompiledBenchmark(addr, inp, exp, gas, bench)
}
+
func BenchmarkPrecompiledSha256(bench *testing.B) {
var (
addr = "02"
@@ -112,6 +113,7 @@ func BenchmarkPrecompiledSha256(bench *testing.B) {
)
precompiledBenchmark(addr, inp, exp, gas, bench)
}
+
func BenchmarkPrecompiledRipeMD(bench *testing.B) {
var (
addr = "03"
@@ -121,6 +123,7 @@ func BenchmarkPrecompiledRipeMD(bench *testing.B) {
)
precompiledBenchmark(addr, inp, exp, gas, bench)
}
+
func BenchmarkPrecompiledIdentity(bench *testing.B) {
var (
addr = "04"
@@ -130,131 +133,171 @@ func BenchmarkPrecompiledIdentity(bench *testing.B) {
)
precompiledBenchmark(addr, inp, exp, gas, bench)
}
+
+func BenchmarkPrecompiledModExp(bench *testing.B) {
+ var (
+ addr = "05"
+ inp = "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002003fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2efffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"
+ exp = "0000000000000000000000000000000000000000000000000000000000000001"
+ gas = uint64(4000000)
+ )
+ precompiledBenchmark(addr, inp, exp, gas, bench)
+}
+
+func BenchmarkPrecompiledBn256Add(bench *testing.B) {
+ var (
+ addr = "06"
+ inp = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ exp = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ gas = uint64(4000000)
+ )
+ precompiledBenchmark(addr, inp, exp, gas, bench)
+}
+
+func BenchmarkPrecompiledBn256ScalarMul(bench *testing.B) {
+ var (
+ addr = "07"
+ inp = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ exp = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ gas = uint64(4000000)
+ )
+ precompiledBenchmark(addr, inp, exp, gas, bench)
+}
+
+func BenchmarkPrecompiledBn256Pairing(bench *testing.B) {
+ var (
+ addr = "08"
+ inp = "1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f593034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf704bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a416782bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
+ exp = "0000000000000000000000000000000000000000000000000000000000000001"
+ gas = uint64(4000000)
+ )
+ precompiledBenchmark(addr, inp, exp, gas, bench)
+}
+
func BenchmarkOpAdd(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opAdd, x, y)
-
}
+
func BenchmarkOpSub(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opSub, x, y)
-
}
+
func BenchmarkOpMul(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opMul, x, y)
-
}
+
func BenchmarkOpDiv(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opDiv, x, y)
-
}
+
func BenchmarkOpSdiv(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opSdiv, x, y)
-
}
+
func BenchmarkOpMod(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opMod, x, y)
-
}
+
func BenchmarkOpSmod(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opSmod, x, y)
-
}
+
func BenchmarkOpExp(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opExp, x, y)
-
}
+
func BenchmarkOpSignExtend(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opSignExtend, x, y)
-
}
+
func BenchmarkOpLt(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opLt, x, y)
-
}
+
func BenchmarkOpGt(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opGt, x, y)
-
}
+
func BenchmarkOpSlt(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opSlt, x, y)
-
}
+
func BenchmarkOpSgt(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opSgt, x, y)
-
}
+
func BenchmarkOpEq(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opEq, x, y)
-
}
+
func BenchmarkOpAnd(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opAnd, x, y)
-
}
+
func BenchmarkOpOr(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opOr, x, y)
-
}
+
func BenchmarkOpXor(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opXor, x, y)
-
}
+
func BenchmarkOpByte(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opByte, x, y)
-
}
func BenchmarkOpAddmod(b *testing.B) {
@@ -263,15 +306,14 @@ func BenchmarkOpAddmod(b *testing.B) {
z := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opAddmod, x, y, z)
-
}
+
func BenchmarkOpMulmod(b *testing.B) {
x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
z := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff"
opBenchmark(b, opMulmod, x, y, z)
-
}
//func BenchmarkOpSha3(b *testing.B) {