github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/core/evm.go (about)

     1  // Copyright 2021 The adkgo Authors
     2  // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8).
     3  //
     4  // the adkgo 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 adkgo 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 adkgo library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"math/big"
    21  	"strconv"
    22    "os"
    23  	"github.com/aidoskuneen/adk-node/common"
    24  	"github.com/aidoskuneen/adk-node/consensus"
    25  	"github.com/aidoskuneen/adk-node/core/types"
    26  	"github.com/aidoskuneen/adk-node/core/vm"
    27  )
    28  
    29  // ChainContext supports retrieving headers and consensus parameters from the
    30  // current blockchain to be used during transaction processing.
    31  type ChainContext interface {
    32  	// Engine retrieves the chain's consensus engine.
    33  	Engine() consensus.Engine
    34  
    35  	// GetHeader returns the hash corresponding to their hash.
    36  	GetHeader(common.Hash, uint64) *types.Header
    37  }
    38  
    39  // NewEVMBlockContext creates a new context for use in the EVM.
    40  func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext {
    41  	var (
    42  		beneficiary common.Address
    43  		baseFee     *big.Int
    44  	)
    45  
    46  	// If we don't have an explicit author (i.e. not mining), extract from the header
    47  	if author == nil {
    48  		beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation
    49  	} else {
    50  		beneficiary = *author
    51  	}
    52  	if header.BaseFee != nil {
    53  		baseFee = new(big.Int).Set(header.BaseFee)
    54  	}
    55  	return vm.BlockContext{
    56  		CanTransfer: CanTransfer,
    57  		Transfer:    Transfer,
    58  		GetHash:     GetHashFn(header, chain),
    59  		Coinbase:    beneficiary,
    60  		BlockNumber: new(big.Int).Set(header.Number),
    61  		Time:        new(big.Int).SetUint64(header.Time),
    62  		Difficulty:  new(big.Int).Set(header.Difficulty),
    63  		BaseFee:     baseFee,
    64  		GasLimit:    header.GasLimit,
    65  	}
    66  }
    67  
    68  // NewEVMTxContext creates a new transaction context for a single transaction.
    69  func NewEVMTxContext(msg Message) vm.TxContext {
    70  	return vm.TxContext{
    71  		Origin:   msg.From(),
    72  		GasPrice: new(big.Int).Set(msg.GasPrice()),
    73  	}
    74  }
    75  
    76  // GetHashFn returns a GetHashFunc which retrieves header hashes by number
    77  func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
    78  	// Cache will initially contain [refHash.parent],
    79  	// Then fill up with [refHash.p, refHash.pp, refHash.ppp, ...]
    80  	var cache []common.Hash
    81  
    82  	return func(n uint64) common.Hash {
    83  		// If there's no hash cache yet, make one
    84  		if len(cache) == 0 {
    85  			cache = append(cache, ref.ParentHash)
    86  		}
    87  		if idx := ref.Number.Uint64() - n - 1; idx < uint64(len(cache)) {
    88  			return cache[idx]
    89  		}
    90  		// No luck in the cache, but we can start iterating from the last element we already know
    91  		lastKnownHash := cache[len(cache)-1]
    92  		lastKnownNumber := ref.Number.Uint64() - uint64(len(cache))
    93  
    94  		for {
    95  			header := chain.GetHeader(lastKnownHash, lastKnownNumber)
    96  			if header == nil {
    97  				break
    98  			}
    99  			cache = append(cache, header.ParentHash)
   100  			lastKnownHash = header.ParentHash
   101  			lastKnownNumber = header.Number.Uint64() - 1
   102  			if n == lastKnownNumber {
   103  				return lastKnownHash
   104  			}
   105  		}
   106  		return common.Hash{}
   107  	}
   108  }
   109  
   110  // CanTransfer checks whether there are enough funds in the address' account to make a transfer.
   111  // This does not take the necessary gas in to account to make the transfer valid.
   112  func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
   113  	return db.GetBalance(addr).Cmp(amount) >= 0
   114  }
   115  
   116  // Transfer subtracts amount from sender and adds amount to recipient using the given Db
   117  func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
   118  	db.SubBalance(sender, amount)
   119  	db.AddBalance(recipient, amount)
   120  
   121  	// log all transfers
   122  	logLine := db.GetHash().Hex() +","+strconv.Itoa(db.GetInternalCounter())+","+sender.Hex()+","+recipient.Hex()+","+amount.String()
   123  
   124  	f, err := os.OpenFile("adk_value_transfer.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
   125  		if err != nil {
   126  			return // ignore error
   127  		}
   128  		defer f.Close()
   129      f.WriteString(logLine+"\n");
   130  
   131  }