github.hscsec.cn/scroll-tech/go-ethereum@v1.9.7/core/vm/contracts.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package vm 18 19 import ( 20 "crypto/sha256" 21 "encoding/binary" 22 "errors" 23 "math/big" 24 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/common/math" 27 "github.com/ethereum/go-ethereum/crypto" 28 "github.com/ethereum/go-ethereum/crypto/blake2b" 29 "github.com/ethereum/go-ethereum/crypto/bn256" 30 "github.com/ethereum/go-ethereum/params" 31 "golang.org/x/crypto/ripemd160" 32 ) 33 34 // PrecompiledContract is the basic interface for native Go contracts. The implementation 35 // requires a deterministic gas count based on the input size of the Run method of the 36 // contract. 37 type PrecompiledContract interface { 38 RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use 39 Run(input []byte) ([]byte, error) // Run runs the precompiled contract 40 } 41 42 // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum 43 // contracts used in the Frontier and Homestead releases. 44 var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{ 45 common.BytesToAddress([]byte{1}): &ecrecover{}, 46 common.BytesToAddress([]byte{2}): &sha256hash{}, 47 common.BytesToAddress([]byte{3}): &ripemd160hash{}, 48 common.BytesToAddress([]byte{4}): &dataCopy{}, 49 } 50 51 // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum 52 // contracts used in the Byzantium release. 53 var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{ 54 common.BytesToAddress([]byte{1}): &ecrecover{}, 55 common.BytesToAddress([]byte{2}): &sha256hash{}, 56 common.BytesToAddress([]byte{3}): &ripemd160hash{}, 57 common.BytesToAddress([]byte{4}): &dataCopy{}, 58 common.BytesToAddress([]byte{5}): &bigModExp{}, 59 common.BytesToAddress([]byte{6}): &bn256AddByzantium{}, 60 common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{}, 61 common.BytesToAddress([]byte{8}): &bn256PairingByzantium{}, 62 } 63 64 // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum 65 // contracts used in the Istanbul release. 66 var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{ 67 common.BytesToAddress([]byte{1}): &ecrecover{}, 68 common.BytesToAddress([]byte{2}): &sha256hash{}, 69 common.BytesToAddress([]byte{3}): &ripemd160hash{}, 70 common.BytesToAddress([]byte{4}): &dataCopy{}, 71 common.BytesToAddress([]byte{5}): &bigModExp{}, 72 common.BytesToAddress([]byte{6}): &bn256AddIstanbul{}, 73 common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{}, 74 common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{}, 75 common.BytesToAddress([]byte{9}): &blake2F{}, 76 } 77 78 // RunPrecompiledContract runs and evaluates the output of a precompiled contract. 79 func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) { 80 gas := p.RequiredGas(input) 81 if contract.UseGas(gas) { 82 return p.Run(input) 83 } 84 return nil, ErrOutOfGas 85 } 86 87 // ECRECOVER implemented as a native contract. 88 type ecrecover struct{} 89 90 func (c *ecrecover) RequiredGas(input []byte) uint64 { 91 return params.EcrecoverGas 92 } 93 94 func (c *ecrecover) Run(input []byte) ([]byte, error) { 95 const ecRecoverInputLength = 128 96 97 input = common.RightPadBytes(input, ecRecoverInputLength) 98 // "input" is (hash, v, r, s), each 32 bytes 99 // but for ecrecover we want (r, s, v) 100 101 r := new(big.Int).SetBytes(input[64:96]) 102 s := new(big.Int).SetBytes(input[96:128]) 103 v := input[63] - 27 104 105 // tighter sig s values input homestead only apply to tx sigs 106 if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) { 107 return nil, nil 108 } 109 // We must make sure not to modify the 'input', so placing the 'v' along with 110 // the signature needs to be done on a new allocation 111 sig := make([]byte, 65) 112 copy(sig, input[64:128]) 113 sig[64] = v 114 // v needs to be at the end for libsecp256k1 115 pubKey, err := crypto.Ecrecover(input[:32], sig) 116 // make sure the public key is a valid one 117 if err != nil { 118 return nil, nil 119 } 120 121 // the first byte of pubkey is bitcoin heritage 122 return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil 123 } 124 125 // SHA256 implemented as a native contract. 126 type sha256hash struct{} 127 128 // RequiredGas returns the gas required to execute the pre-compiled contract. 129 // 130 // This method does not require any overflow checking as the input size gas costs 131 // required for anything significant is so high it's impossible to pay for. 132 func (c *sha256hash) RequiredGas(input []byte) uint64 { 133 return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas 134 } 135 func (c *sha256hash) Run(input []byte) ([]byte, error) { 136 h := sha256.Sum256(input) 137 return h[:], nil 138 } 139 140 // RIPEMD160 implemented as a native contract. 141 type ripemd160hash struct{} 142 143 // RequiredGas returns the gas required to execute the pre-compiled contract. 144 // 145 // This method does not require any overflow checking as the input size gas costs 146 // required for anything significant is so high it's impossible to pay for. 147 func (c *ripemd160hash) RequiredGas(input []byte) uint64 { 148 return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas 149 } 150 func (c *ripemd160hash) Run(input []byte) ([]byte, error) { 151 ripemd := ripemd160.New() 152 ripemd.Write(input) 153 return common.LeftPadBytes(ripemd.Sum(nil), 32), nil 154 } 155 156 // data copy implemented as a native contract. 157 type dataCopy struct{} 158 159 // RequiredGas returns the gas required to execute the pre-compiled contract. 160 // 161 // This method does not require any overflow checking as the input size gas costs 162 // required for anything significant is so high it's impossible to pay for. 163 func (c *dataCopy) RequiredGas(input []byte) uint64 { 164 return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas 165 } 166 func (c *dataCopy) Run(in []byte) ([]byte, error) { 167 return in, nil 168 } 169 170 // bigModExp implements a native big integer exponential modular operation. 171 type bigModExp struct{} 172 173 var ( 174 big1 = big.NewInt(1) 175 big4 = big.NewInt(4) 176 big8 = big.NewInt(8) 177 big16 = big.NewInt(16) 178 big32 = big.NewInt(32) 179 big64 = big.NewInt(64) 180 big96 = big.NewInt(96) 181 big480 = big.NewInt(480) 182 big1024 = big.NewInt(1024) 183 big3072 = big.NewInt(3072) 184 big199680 = big.NewInt(199680) 185 ) 186 187 // RequiredGas returns the gas required to execute the pre-compiled contract. 188 func (c *bigModExp) RequiredGas(input []byte) uint64 { 189 var ( 190 baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) 191 expLen = new(big.Int).SetBytes(getData(input, 32, 32)) 192 modLen = new(big.Int).SetBytes(getData(input, 64, 32)) 193 ) 194 if len(input) > 96 { 195 input = input[96:] 196 } else { 197 input = input[:0] 198 } 199 // Retrieve the head 32 bytes of exp for the adjusted exponent length 200 var expHead *big.Int 201 if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 { 202 expHead = new(big.Int) 203 } else { 204 if expLen.Cmp(big32) > 0 { 205 expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32)) 206 } else { 207 expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64())) 208 } 209 } 210 // Calculate the adjusted exponent length 211 var msb int 212 if bitlen := expHead.BitLen(); bitlen > 0 { 213 msb = bitlen - 1 214 } 215 adjExpLen := new(big.Int) 216 if expLen.Cmp(big32) > 0 { 217 adjExpLen.Sub(expLen, big32) 218 adjExpLen.Mul(big8, adjExpLen) 219 } 220 adjExpLen.Add(adjExpLen, big.NewInt(int64(msb))) 221 222 // Calculate the gas cost of the operation 223 gas := new(big.Int).Set(math.BigMax(modLen, baseLen)) 224 switch { 225 case gas.Cmp(big64) <= 0: 226 gas.Mul(gas, gas) 227 case gas.Cmp(big1024) <= 0: 228 gas = new(big.Int).Add( 229 new(big.Int).Div(new(big.Int).Mul(gas, gas), big4), 230 new(big.Int).Sub(new(big.Int).Mul(big96, gas), big3072), 231 ) 232 default: 233 gas = new(big.Int).Add( 234 new(big.Int).Div(new(big.Int).Mul(gas, gas), big16), 235 new(big.Int).Sub(new(big.Int).Mul(big480, gas), big199680), 236 ) 237 } 238 gas.Mul(gas, math.BigMax(adjExpLen, big1)) 239 gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv)) 240 241 if gas.BitLen() > 64 { 242 return math.MaxUint64 243 } 244 return gas.Uint64() 245 } 246 247 func (c *bigModExp) Run(input []byte) ([]byte, error) { 248 var ( 249 baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64() 250 expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64() 251 modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64() 252 ) 253 if len(input) > 96 { 254 input = input[96:] 255 } else { 256 input = input[:0] 257 } 258 // Handle a special case when both the base and mod length is zero 259 if baseLen == 0 && modLen == 0 { 260 return []byte{}, nil 261 } 262 // Retrieve the operands and execute the exponentiation 263 var ( 264 base = new(big.Int).SetBytes(getData(input, 0, baseLen)) 265 exp = new(big.Int).SetBytes(getData(input, baseLen, expLen)) 266 mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen)) 267 ) 268 if mod.BitLen() == 0 { 269 // Modulo 0 is undefined, return zero 270 return common.LeftPadBytes([]byte{}, int(modLen)), nil 271 } 272 return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil 273 } 274 275 // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point, 276 // returning it, or an error if the point is invalid. 277 func newCurvePoint(blob []byte) (*bn256.G1, error) { 278 p := new(bn256.G1) 279 if _, err := p.Unmarshal(blob); err != nil { 280 return nil, err 281 } 282 return p, nil 283 } 284 285 // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point, 286 // returning it, or an error if the point is invalid. 287 func newTwistPoint(blob []byte) (*bn256.G2, error) { 288 p := new(bn256.G2) 289 if _, err := p.Unmarshal(blob); err != nil { 290 return nil, err 291 } 292 return p, nil 293 } 294 295 // runBn256Add implements the Bn256Add precompile, referenced by both 296 // Byzantium and Istanbul operations. 297 func runBn256Add(input []byte) ([]byte, error) { 298 x, err := newCurvePoint(getData(input, 0, 64)) 299 if err != nil { 300 return nil, err 301 } 302 y, err := newCurvePoint(getData(input, 64, 64)) 303 if err != nil { 304 return nil, err 305 } 306 res := new(bn256.G1) 307 res.Add(x, y) 308 return res.Marshal(), nil 309 } 310 311 // bn256Add implements a native elliptic curve point addition conforming to 312 // Istanbul consensus rules. 313 type bn256AddIstanbul struct{} 314 315 // RequiredGas returns the gas required to execute the pre-compiled contract. 316 func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 { 317 return params.Bn256AddGasIstanbul 318 } 319 320 func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) { 321 return runBn256Add(input) 322 } 323 324 // bn256AddByzantium implements a native elliptic curve point addition 325 // conforming to Byzantium consensus rules. 326 type bn256AddByzantium struct{} 327 328 // RequiredGas returns the gas required to execute the pre-compiled contract. 329 func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 { 330 return params.Bn256AddGasByzantium 331 } 332 333 func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) { 334 return runBn256Add(input) 335 } 336 337 // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by 338 // both Byzantium and Istanbul operations. 339 func runBn256ScalarMul(input []byte) ([]byte, error) { 340 p, err := newCurvePoint(getData(input, 0, 64)) 341 if err != nil { 342 return nil, err 343 } 344 res := new(bn256.G1) 345 res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32))) 346 return res.Marshal(), nil 347 } 348 349 // bn256ScalarMulIstanbul implements a native elliptic curve scalar 350 // multiplication conforming to Istanbul consensus rules. 351 type bn256ScalarMulIstanbul struct{} 352 353 // RequiredGas returns the gas required to execute the pre-compiled contract. 354 func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 { 355 return params.Bn256ScalarMulGasIstanbul 356 } 357 358 func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) { 359 return runBn256ScalarMul(input) 360 } 361 362 // bn256ScalarMulByzantium implements a native elliptic curve scalar 363 // multiplication conforming to Byzantium consensus rules. 364 type bn256ScalarMulByzantium struct{} 365 366 // RequiredGas returns the gas required to execute the pre-compiled contract. 367 func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 { 368 return params.Bn256ScalarMulGasByzantium 369 } 370 371 func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) { 372 return runBn256ScalarMul(input) 373 } 374 375 var ( 376 // true32Byte is returned if the bn256 pairing check succeeds. 377 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} 378 379 // false32Byte is returned if the bn256 pairing check fails. 380 false32Byte = make([]byte, 32) 381 382 // errBadPairingInput is returned if the bn256 pairing input is invalid. 383 errBadPairingInput = errors.New("bad elliptic curve pairing size") 384 ) 385 386 // runBn256Pairing implements the Bn256Pairing precompile, referenced by both 387 // Byzantium and Istanbul operations. 388 func runBn256Pairing(input []byte) ([]byte, error) { 389 // Handle some corner cases cheaply 390 if len(input)%192 > 0 { 391 return nil, errBadPairingInput 392 } 393 // Convert the input into a set of coordinates 394 var ( 395 cs []*bn256.G1 396 ts []*bn256.G2 397 ) 398 for i := 0; i < len(input); i += 192 { 399 c, err := newCurvePoint(input[i : i+64]) 400 if err != nil { 401 return nil, err 402 } 403 t, err := newTwistPoint(input[i+64 : i+192]) 404 if err != nil { 405 return nil, err 406 } 407 cs = append(cs, c) 408 ts = append(ts, t) 409 } 410 // Execute the pairing checks and return the results 411 if bn256.PairingCheck(cs, ts) { 412 return true32Byte, nil 413 } 414 return false32Byte, nil 415 } 416 417 // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve 418 // conforming to Istanbul consensus rules. 419 type bn256PairingIstanbul struct{} 420 421 // RequiredGas returns the gas required to execute the pre-compiled contract. 422 func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 { 423 return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul 424 } 425 426 func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) { 427 return runBn256Pairing(input) 428 } 429 430 // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve 431 // conforming to Byzantium consensus rules. 432 type bn256PairingByzantium struct{} 433 434 // RequiredGas returns the gas required to execute the pre-compiled contract. 435 func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 { 436 return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium 437 } 438 439 func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) { 440 return runBn256Pairing(input) 441 } 442 443 type blake2F struct{} 444 445 func (c *blake2F) RequiredGas(input []byte) uint64 { 446 // If the input is malformed, we can't calculate the gas, return 0 and let the 447 // actual call choke and fault. 448 if len(input) != blake2FInputLength { 449 return 0 450 } 451 return uint64(binary.BigEndian.Uint32(input[0:4])) 452 } 453 454 const ( 455 blake2FInputLength = 213 456 blake2FFinalBlockBytes = byte(1) 457 blake2FNonFinalBlockBytes = byte(0) 458 ) 459 460 var ( 461 errBlake2FInvalidInputLength = errors.New("invalid input length") 462 errBlake2FInvalidFinalFlag = errors.New("invalid final flag") 463 ) 464 465 func (c *blake2F) Run(input []byte) ([]byte, error) { 466 // Make sure the input is valid (correct lenth and final flag) 467 if len(input) != blake2FInputLength { 468 return nil, errBlake2FInvalidInputLength 469 } 470 if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes { 471 return nil, errBlake2FInvalidFinalFlag 472 } 473 // Parse the input into the Blake2b call parameters 474 var ( 475 rounds = binary.BigEndian.Uint32(input[0:4]) 476 final = (input[212] == blake2FFinalBlockBytes) 477 478 h [8]uint64 479 m [16]uint64 480 t [2]uint64 481 ) 482 for i := 0; i < 8; i++ { 483 offset := 4 + i*8 484 h[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) 485 } 486 for i := 0; i < 16; i++ { 487 offset := 68 + i*8 488 m[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) 489 } 490 t[0] = binary.LittleEndian.Uint64(input[196:204]) 491 t[1] = binary.LittleEndian.Uint64(input[204:212]) 492 493 // Execute the compression function, extract and return the result 494 blake2b.F(&h, m, t, final, rounds) 495 496 output := make([]byte, 64) 497 for i := 0; i < 8; i++ { 498 offset := i * 8 499 binary.LittleEndian.PutUint64(output[offset:offset+8], h[i]) 500 } 501 return output, nil 502 }