github.com/amazechain/amc@v0.1.3/internal/vm/gas_table.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package vm 18 19 import ( 20 "errors" 21 "github.com/amazechain/amc/common/types" 22 "github.com/amazechain/amc/internal/vm/stack" 23 "github.com/amazechain/amc/params" 24 25 "github.com/amazechain/amc/common/math" 26 "github.com/holiman/uint256" 27 ) 28 29 // memoryGasCost calculates the quadratic gas for memory expansion. It does so 30 // only for the memory region that is expanded, not the total memory. 31 func memoryGasCost(mem *Memory, newMemSize uint64) (uint64, error) { 32 if newMemSize == 0 { 33 return 0, nil 34 } 35 // The maximum that will fit in a uint64 is max_word_count - 1. Anything above 36 // that will result in an overflow. Additionally, a newMemSize which results in 37 // a newMemSizeWords larger than 0xFFFFFFFF will cause the square operation to 38 // overflow. The constant 0x1FFFFFFFE0 is the highest number that can be used 39 // without overflowing the gas calculation. 40 if newMemSize > 0x1FFFFFFFE0 { 41 return 0, ErrGasUintOverflow 42 } 43 newMemSizeWords := ToWordSize(newMemSize) 44 newMemSize = newMemSizeWords * 32 45 46 if newMemSize > uint64(mem.Len()) { 47 square := newMemSizeWords * newMemSizeWords 48 linCoef := newMemSizeWords * params.MemoryGas 49 quadCoef := square / params.QuadCoeffDiv 50 newTotalFee := linCoef + quadCoef 51 52 fee := newTotalFee - mem.lastGasCost 53 mem.lastGasCost = newTotalFee 54 55 return fee, nil 56 } 57 return 0, nil 58 } 59 60 // memoryCopierGas creates the gas functions for the following opcodes, and takes 61 // the stack position of the operand which determines the size of the data to copy 62 // as argument: 63 // CALLDATACOPY (stack position 2) 64 // CODECOPY (stack position 2) 65 // EXTCODECOPY (stack poition 3) 66 // RETURNDATACOPY (stack position 2) 67 func memoryCopierGas(stackpos int) gasFunc { 68 return func(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 69 // Gas for expanding the memory 70 gas, err := memoryGasCost(mem, memorySize) 71 if err != nil { 72 return 0, err 73 } 74 // And gas for copying data, charged per word at param.CopyGas 75 words, overflow := stack.Back(stackpos).Uint64WithOverflow() 76 if overflow { 77 return 0, ErrGasUintOverflow 78 } 79 80 if words, overflow = math.SafeMul(ToWordSize(words), params.CopyGas); overflow { 81 return 0, ErrGasUintOverflow 82 } 83 84 if gas, overflow = math.SafeAdd(gas, words); overflow { 85 return 0, ErrGasUintOverflow 86 } 87 return gas, nil 88 } 89 } 90 91 var ( 92 gasCallDataCopy = memoryCopierGas(2) 93 gasCodeCopy = memoryCopierGas(2) 94 gasExtCodeCopy = memoryCopierGas(3) 95 gasReturnDataCopy = memoryCopierGas(2) 96 ) 97 98 func gasSStore(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 99 value, x := stack.Back(1), stack.Back(0) 100 key := types.Hash(x.Bytes32()) 101 var current uint256.Int 102 evm.IntraBlockState().GetState(contract.Address(), &key, ¤t) 103 // The legacy gas metering only takes into consideration the current state 104 // Legacy rules should be applied if we are in Petersburg (removal of EIP-1283) 105 // OR Constantinople is not active 106 if evm.ChainRules().IsPetersburg || !evm.ChainRules().IsConstantinople { 107 // This checks for 3 scenario's and calculates gas accordingly: 108 // 109 // 1. From a zero-value address to a non-zero value (NEW VALUE) 110 // 2. From a non-zero value address to a zero-value address (DELETE) 111 // 3. From a non-zero to a non-zero (CHANGE) 112 switch { 113 case current.IsZero() && !value.IsZero(): // 0 => non 0 114 return params.SstoreSetGas, nil 115 case !current.IsZero() && value.IsZero(): // non 0 => 0 116 evm.IntraBlockState().AddRefund(params.SstoreRefundGas) 117 return params.SstoreClearGas, nil 118 default: // non 0 => non 0 (or 0 => 0) 119 return params.SstoreResetGas, nil 120 } 121 } 122 // The new gas metering is based on net gas costs (EIP-1283): 123 // 124 // 1. If current value equals new value (this is a no-op), 200 gas is deducted. 125 // 2. If current value does not equal new value 126 // 2.1. If original value equals current value (this storage slot has not been changed by the current execution context) 127 // 2.1.1. If original value is 0, 20000 gas is deducted. 128 // 2.1.2. Otherwise, 5000 gas is deducted. If new value is 0, add 15000 gas to refund counter. 129 // 2.2. If original value does not equal current value (this storage slot is dirty), 200 gas is deducted. Apply both of the following clauses. 130 // 2.2.1. If original value is not 0 131 // 2.2.1.1. If current value is 0 (also means that new value is not 0), remove 15000 gas from refund counter. We can prove that refund counter will never go below 0. 132 // 2.2.1.2. If new value is 0 (also means that current value is not 0), add 15000 gas to refund counter. 133 // 2.2.2. If original value equals new value (this storage slot is reset) 134 // 2.2.2.1. If original value is 0, add 19800 gas to refund counter. 135 // 2.2.2.2. Otherwise, add 4800 gas to refund counter. 136 if current.Eq(value) { // noop (1) 137 return params.NetSstoreNoopGas, nil 138 } 139 var original uint256.Int 140 evm.IntraBlockState().GetCommittedState(contract.Address(), &key, &original) 141 if original == current { 142 if original.IsZero() { // create slot (2.1.1) 143 return params.NetSstoreInitGas, nil 144 } 145 if value.IsZero() { // delete slot (2.1.2b) 146 evm.IntraBlockState().AddRefund(params.NetSstoreClearRefund) 147 } 148 return params.NetSstoreCleanGas, nil // write existing slot (2.1.2) 149 } 150 if !original.IsZero() { 151 if current.IsZero() { // recreate slot (2.2.1.1) 152 evm.IntraBlockState().SubRefund(params.NetSstoreClearRefund) 153 } else if value.IsZero() { // delete slot (2.2.1.2) 154 evm.IntraBlockState().AddRefund(params.NetSstoreClearRefund) 155 } 156 } 157 if original.Eq(value) { 158 if original.IsZero() { // reset to original inexistent slot (2.2.2.1) 159 evm.IntraBlockState().AddRefund(params.NetSstoreResetClearRefund) 160 } else { // reset to original existing slot (2.2.2.2) 161 evm.IntraBlockState().AddRefund(params.NetSstoreResetRefund) 162 } 163 } 164 165 return params.NetSstoreDirtyGas, nil 166 } 167 168 // 0. If *gasleft* is less than or equal to 2300, fail the current call. 169 // 1. If current value equals new value (this is a no-op), SLOAD_GAS is deducted. 170 // 2. If current value does not equal new value: 171 // 2.1. If original value equals current value (this storage slot has not been changed by the current execution context): 172 // 2.1.1. If original value is 0, SSTORE_SET_GAS (20K) gas is deducted. 173 // 2.1.2. Otherwise, SSTORE_RESET_GAS gas is deducted. If new value is 0, add SSTORE_CLEARS_SCHEDULE to refund counter. 174 // 2.2. If original value does not equal current value (this storage slot is dirty), SLOAD_GAS gas is deducted. Apply both of the following clauses: 175 // 2.2.1. If original value is not 0: 176 // 2.2.1.1. If current value is 0 (also means that new value is not 0), subtract SSTORE_CLEARS_SCHEDULE gas from refund counter. 177 // 2.2.1.2. If new value is 0 (also means that current value is not 0), add SSTORE_CLEARS_SCHEDULE gas to refund counter. 178 // 2.2.2. If original value equals new value (this storage slot is reset): 179 // 2.2.2.1. If original value is 0, add SSTORE_SET_GAS - SLOAD_GAS to refund counter. 180 // 2.2.2.2. Otherwise, add SSTORE_RESET_GAS - SLOAD_GAS gas to refund counter. 181 func gasSStoreEIP2200(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 182 // If we fail the minimum gas availability invariant, fail (0) 183 if contract.Gas <= params.SstoreSentryGasEIP2200 { 184 return 0, errors.New("not enough gas for reentrancy sentry") 185 } 186 // Gas sentry honoured, do the actual gas calculation based on the stored value 187 value, x := stack.Back(1), stack.Back(0) 188 key := types.Hash(x.Bytes32()) 189 var current uint256.Int 190 evm.IntraBlockState().GetState(contract.Address(), &key, ¤t) 191 192 if current.Eq(value) { // noop (1) 193 return params.SloadGasEIP2200, nil 194 } 195 196 var original uint256.Int 197 evm.IntraBlockState().GetCommittedState(contract.Address(), &key, &original) 198 if original == current { 199 if original.IsZero() { // create slot (2.1.1) 200 return params.SstoreSetGasEIP2200, nil 201 } 202 if value.IsZero() { // delete slot (2.1.2b) 203 evm.IntraBlockState().AddRefund(params.SstoreClearsScheduleRefundEIP2200) 204 } 205 return params.SstoreResetGasEIP2200, nil // write existing slot (2.1.2) 206 } 207 if !original.IsZero() { 208 if current.IsZero() { // recreate slot (2.2.1.1) 209 evm.IntraBlockState().SubRefund(params.SstoreClearsScheduleRefundEIP2200) 210 } else if value.IsZero() { // delete slot (2.2.1.2) 211 evm.IntraBlockState().AddRefund(params.SstoreClearsScheduleRefundEIP2200) 212 } 213 } 214 if original.Eq(value) { 215 if original.IsZero() { // reset to original inexistent slot (2.2.2.1) 216 evm.IntraBlockState().AddRefund(params.SstoreSetGasEIP2200 - params.SloadGasEIP2200) 217 } else { // reset to original existing slot (2.2.2.2) 218 evm.IntraBlockState().AddRefund(params.SstoreResetGasEIP2200 - params.SloadGasEIP2200) 219 } 220 } 221 return params.SloadGasEIP2200, nil // dirty update (2.2) 222 } 223 224 func makeGasLog(n uint64) gasFunc { 225 return func(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 226 requestedSize, overflow := stack.Back(1).Uint64WithOverflow() 227 if overflow { 228 return 0, ErrGasUintOverflow 229 } 230 231 gas, err := memoryGasCost(mem, memorySize) 232 if err != nil { 233 return 0, err 234 } 235 236 if gas, overflow = math.SafeAdd(gas, params.LogGas); overflow { 237 return 0, ErrGasUintOverflow 238 } 239 if gas, overflow = math.SafeAdd(gas, n*params.LogTopicGas); overflow { 240 return 0, ErrGasUintOverflow 241 } 242 243 var memorySizeGas uint64 244 if memorySizeGas, overflow = math.SafeMul(requestedSize, params.LogDataGas); overflow { 245 return 0, ErrGasUintOverflow 246 } 247 if gas, overflow = math.SafeAdd(gas, memorySizeGas); overflow { 248 return 0, ErrGasUintOverflow 249 } 250 return gas, nil 251 } 252 } 253 254 func gasKeccak256(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 255 gas, err := memoryGasCost(mem, memorySize) 256 if err != nil { 257 return 0, err 258 } 259 wordGas, overflow := stack.Back(1).Uint64WithOverflow() 260 if overflow { 261 return 0, ErrGasUintOverflow 262 } 263 if wordGas, overflow = math.SafeMul(ToWordSize(wordGas), params.Keccak256WordGas); overflow { 264 return 0, ErrGasUintOverflow 265 } 266 if gas, overflow = math.SafeAdd(gas, wordGas); overflow { 267 return 0, ErrGasUintOverflow 268 } 269 return gas, nil 270 } 271 272 // pureMemoryGascost is used by several operations, which aside from their 273 // static cost have a dynamic cost which is solely based on the memory 274 // expansion 275 func pureMemoryGascost(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 276 return memoryGasCost(mem, memorySize) 277 } 278 279 var ( 280 gasReturn = pureMemoryGascost 281 gasRevert = pureMemoryGascost 282 gasMLoad = pureMemoryGascost 283 gasMStore8 = pureMemoryGascost 284 gasMStore = pureMemoryGascost 285 gasCreate = pureMemoryGascost 286 ) 287 288 func gasCreate2(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 289 gas, err := memoryGasCost(mem, memorySize) 290 if err != nil { 291 return 0, err 292 } 293 len, overflow := stack.Back(2).Uint64WithOverflow() 294 if overflow { 295 return 0, ErrGasUintOverflow 296 } 297 numWords := ToWordSize(len) 298 wordGas, overflow := math.SafeMul(numWords, params.Keccak256WordGas) 299 if overflow { 300 return 0, ErrGasUintOverflow 301 } 302 gas, overflow = math.SafeAdd(gas, wordGas) 303 if overflow { 304 return 0, ErrGasUintOverflow 305 } 306 return gas, nil 307 } 308 309 func gasCreateEip3860(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 310 gas, err := memoryGasCost(mem, memorySize) 311 if err != nil { 312 return 0, err 313 } 314 len, overflow := stack.Back(2).Uint64WithOverflow() 315 if overflow || len > params.MaxInitCodeSize { 316 return 0, ErrGasUintOverflow 317 } 318 numWords := ToWordSize(len) 319 // Since size <= params.MaxInitCodeSize, this multiplication cannot overflow 320 wordGas := params.InitCodeWordGas * numWords 321 gas, overflow = math.SafeAdd(gas, wordGas) 322 if overflow { 323 return 0, ErrGasUintOverflow 324 } 325 return gas, nil 326 } 327 328 func gasCreate2Eip3860(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 329 gas, err := memoryGasCost(mem, memorySize) 330 if err != nil { 331 return 0, err 332 } 333 len, overflow := stack.Back(2).Uint64WithOverflow() 334 if overflow || len > params.MaxInitCodeSize { 335 return 0, ErrGasUintOverflow 336 } 337 numWords := ToWordSize(len) 338 // Since size <= params.MaxInitCodeSize, this multiplication cannot overflow 339 wordGas := (params.InitCodeWordGas + params.Keccak256WordGas) * numWords 340 gas, overflow = math.SafeAdd(gas, wordGas) 341 if overflow { 342 return 0, ErrGasUintOverflow 343 } 344 return gas, nil 345 } 346 347 func gasExpFrontier(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 348 expByteLen := uint64((stack.Data[stack.Len()-2].BitLen() + 7) / 8) 349 350 var ( 351 gas = expByteLen * params.ExpByteFrontier // no overflow check required. Max is 256 * ExpByte gas 352 overflow bool 353 ) 354 if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow { 355 return 0, ErrGasUintOverflow 356 } 357 return gas, nil 358 } 359 360 func gasExpEIP160(_ VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 361 expByteLen := uint64((stack.Data[stack.Len()-2].BitLen() + 7) / 8) 362 363 var ( 364 gas = expByteLen * params.ExpByteEIP160 // no overflow check required. Max is 256 * ExpByte gas 365 overflow bool 366 ) 367 if gas, overflow = math.SafeAdd(gas, params.ExpGas); overflow { 368 return 0, ErrGasUintOverflow 369 } 370 return gas, nil 371 } 372 373 func gasCall(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 374 var ( 375 gas uint64 376 transfersValue = !stack.Back(2).IsZero() 377 address = types.Address(stack.Back(1).Bytes20()) 378 ) 379 if evm.ChainRules().IsSpuriousDragon { 380 if transfersValue && evm.IntraBlockState().Empty(address) { 381 gas += params.CallNewAccountGas 382 } 383 } else if !evm.IntraBlockState().Exist(address) { 384 gas += params.CallNewAccountGas 385 } 386 if transfersValue { 387 gas += params.CallValueTransferGas 388 } 389 memoryGas, err := memoryGasCost(mem, memorySize) 390 if err != nil { 391 return 0, err 392 } 393 var overflow bool 394 if gas, overflow = math.SafeAdd(gas, memoryGas); overflow { 395 return 0, ErrGasUintOverflow 396 } 397 398 var callGasTemp uint64 399 callGasTemp, err = callGas(evm.ChainRules().IsTangerineWhistle, contract.Gas, gas, stack.Back(0)) 400 evm.SetCallGasTemp(callGasTemp) 401 402 if err != nil { 403 return 0, err 404 } 405 if gas, overflow = math.SafeAdd(gas, callGasTemp); overflow { 406 return 0, ErrGasUintOverflow 407 } 408 return gas, nil 409 } 410 411 func gasCallCode(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 412 memoryGas, err := memoryGasCost(mem, memorySize) 413 if err != nil { 414 return 0, err 415 } 416 var ( 417 gas uint64 418 overflow bool 419 ) 420 if !stack.Back(2).IsZero() { 421 gas += params.CallValueTransferGas 422 } 423 if gas, overflow = math.SafeAdd(gas, memoryGas); overflow { 424 return 0, ErrGasUintOverflow 425 } 426 var callGasTemp uint64 427 callGasTemp, err = callGas(evm.ChainRules().IsTangerineWhistle, contract.Gas, gas, stack.Back(0)) 428 evm.SetCallGasTemp(callGasTemp) 429 430 if err != nil { 431 return 0, err 432 } 433 if gas, overflow = math.SafeAdd(gas, callGasTemp); overflow { 434 return 0, ErrGasUintOverflow 435 } 436 return gas, nil 437 } 438 439 func gasDelegateCall(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 440 gas, err := memoryGasCost(mem, memorySize) 441 if err != nil { 442 return 0, err 443 } 444 445 var callGasTemp uint64 446 callGasTemp, err = callGas(evm.ChainRules().IsTangerineWhistle, contract.Gas, gas, stack.Back(0)) 447 evm.SetCallGasTemp(callGasTemp) 448 449 if err != nil { 450 return 0, err 451 } 452 var overflow bool 453 if gas, overflow = math.SafeAdd(gas, callGasTemp); overflow { 454 return 0, ErrGasUintOverflow 455 } 456 return gas, nil 457 } 458 459 func gasStaticCall(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 460 gas, err := memoryGasCost(mem, memorySize) 461 if err != nil { 462 return 0, err 463 } 464 465 var callGasTemp uint64 466 callGasTemp, err = callGas(evm.ChainRules().IsTangerineWhistle, contract.Gas, gas, stack.Back(0)) 467 evm.SetCallGasTemp(callGasTemp) 468 469 if err != nil { 470 return 0, err 471 } 472 var overflow bool 473 if gas, overflow = math.SafeAdd(gas, callGasTemp); overflow { 474 return 0, ErrGasUintOverflow 475 } 476 return gas, nil 477 } 478 479 func gasSelfdestruct(evm VMInterpreter, contract *Contract, stack *stack.Stack, mem *Memory, memorySize uint64) (uint64, error) { 480 var gas uint64 481 // TangerineWhistle (EIP150) gas reprice fork: 482 if evm.ChainRules().IsTangerineWhistle { 483 gas = params.SelfdestructGasEIP150 484 var address = types.Address(stack.Back(0).Bytes20()) 485 486 if evm.ChainRules().IsSpuriousDragon { 487 // if empty and transfers value 488 if evm.IntraBlockState().Empty(address) && !evm.IntraBlockState().GetBalance(contract.Address()).IsZero() { 489 gas += params.CreateBySelfdestructGas 490 } 491 } else if !evm.IntraBlockState().Exist(address) { 492 gas += params.CreateBySelfdestructGas 493 } 494 } 495 496 if !evm.IntraBlockState().HasSelfdestructed(contract.Address()) { 497 evm.IntraBlockState().AddRefund(params.SelfdestructRefundGas) 498 } 499 return gas, nil 500 }