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