github.com/MetalBlockchain/subnet-evm@v0.4.9/accounts/abi/abi.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package abi
    28  
    29  import (
    30  	"bytes"
    31  	"encoding/json"
    32  	"errors"
    33  	"fmt"
    34  	"io"
    35  
    36  	"github.com/ethereum/go-ethereum/common"
    37  	"github.com/ethereum/go-ethereum/crypto"
    38  )
    39  
    40  // The ABI holds information about a contract's context and available
    41  // invokable methods. It will allow you to type check function calls and
    42  // packs data accordingly.
    43  type ABI struct {
    44  	Constructor Method
    45  	Methods     map[string]Method
    46  	Events      map[string]Event
    47  	Errors      map[string]Error
    48  
    49  	// Additional "special" functions introduced in solidity v0.6.0.
    50  	// It's separated from the original default fallback. Each contract
    51  	// can only define one fallback and receive function.
    52  	Fallback Method // Note it's also used to represent legacy fallback before v0.6.0
    53  	Receive  Method
    54  }
    55  
    56  // JSON returns a parsed ABI interface and error if it failed.
    57  func JSON(reader io.Reader) (ABI, error) {
    58  	dec := json.NewDecoder(reader)
    59  
    60  	var abi ABI
    61  	if err := dec.Decode(&abi); err != nil {
    62  		return ABI{}, err
    63  	}
    64  	return abi, nil
    65  }
    66  
    67  // Pack the given method name to conform the ABI. Method call's data
    68  // will consist of method_id, args0, arg1, ... argN. Method id consists
    69  // of 4 bytes and arguments are all 32 bytes.
    70  // Method ids are created from the first 4 bytes of the hash of the
    71  // methods string signature. (signature = baz(uint32,string32))
    72  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    73  	// Fetch the ABI of the requested method
    74  	if name == "" {
    75  		// constructor
    76  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    77  		if err != nil {
    78  			return nil, err
    79  		}
    80  		return arguments, nil
    81  	}
    82  	method, exist := abi.Methods[name]
    83  	if !exist {
    84  		return nil, fmt.Errorf("method '%s' not found", name)
    85  	}
    86  	arguments, err := method.Inputs.Pack(args...)
    87  	if err != nil {
    88  		return nil, err
    89  	}
    90  	// Pack up the method ID too if not a constructor and return
    91  	return append(method.ID, arguments...), nil
    92  }
    93  
    94  // PackEvent packs the given event name and arguments to conform the ABI.
    95  // Returns the topics for the event including the event signature (if non-anonymous event) and
    96  // hashes derived from indexed arguments and the packed data of non-indexed args according to
    97  // the event ABI specification.
    98  // https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#indexed-event-encoding.
    99  // Note: PackEvent does not support array (fixed or dynamic-size) or struct types.
   100  func (abi ABI) PackEvent(name string, args ...interface{}) ([]common.Hash, []byte, error) {
   101  	event, exist := abi.Events[name]
   102  	if !exist {
   103  		return nil, nil, fmt.Errorf("event '%s' not found", name)
   104  	}
   105  	if len(args) != len(event.Inputs) {
   106  		return nil, nil, fmt.Errorf("event '%s' unexpected number of inputs %d", name, len(args))
   107  	}
   108  
   109  	var (
   110  		nonIndexedInputs = make([]interface{}, 0)
   111  		indexedInputs    = make([]interface{}, 0)
   112  		nonIndexedArgs   Arguments
   113  		indexedArgs      Arguments
   114  	)
   115  
   116  	for i, arg := range event.Inputs {
   117  		if arg.Indexed {
   118  			indexedArgs = append(indexedArgs, arg)
   119  			indexedInputs = append(indexedInputs, args[i])
   120  		} else {
   121  			nonIndexedArgs = append(nonIndexedArgs, arg)
   122  			nonIndexedInputs = append(nonIndexedInputs, args[i])
   123  		}
   124  	}
   125  
   126  	packedArguments, err := nonIndexedArgs.Pack(nonIndexedInputs...)
   127  	if err != nil {
   128  		return nil, nil, err
   129  	}
   130  	topics := make([]common.Hash, 0, len(indexedArgs)+1)
   131  	if !event.Anonymous {
   132  		topics = append(topics, event.ID)
   133  	}
   134  	indexedTopics, err := PackTopics(indexedInputs)
   135  	if err != nil {
   136  		return nil, nil, err
   137  	}
   138  
   139  	return append(topics, indexedTopics...), packedArguments, nil
   140  }
   141  
   142  // PackOutput packs the given [args] as the output of given method [name] to conform the ABI.
   143  // This does not include method ID.
   144  func (abi ABI) PackOutput(name string, args ...interface{}) ([]byte, error) {
   145  	// Fetch the ABI of the requested method
   146  	method, exist := abi.Methods[name]
   147  	if !exist {
   148  		return nil, fmt.Errorf("method '%s' not found", name)
   149  	}
   150  	arguments, err := method.Outputs.Pack(args...)
   151  	if err != nil {
   152  		return nil, err
   153  	}
   154  	return arguments, nil
   155  }
   156  
   157  // getInputs gets input arguments of the given [name] method.
   158  func (abi ABI) getInputs(name string, data []byte) (Arguments, error) {
   159  	// since there can't be naming collisions with contracts and events,
   160  	// we need to decide whether we're calling a method or an event
   161  	var args Arguments
   162  	if method, ok := abi.Methods[name]; ok {
   163  		if len(data)%32 != 0 {
   164  			return nil, fmt.Errorf("abi: improperly formatted input: %s - Bytes: [%+v]", string(data), data)
   165  		}
   166  		args = method.Inputs
   167  	}
   168  	if event, ok := abi.Events[name]; ok {
   169  		args = event.Inputs
   170  	}
   171  	if args == nil {
   172  		return nil, fmt.Errorf("abi: could not locate named method or event: %s", name)
   173  	}
   174  	return args, nil
   175  }
   176  
   177  // getArguments gets output arguments of the given [name] method.
   178  func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
   179  	// since there can't be naming collisions with contracts and events,
   180  	// we need to decide whether we're calling a method or an event
   181  	var args Arguments
   182  	if method, ok := abi.Methods[name]; ok {
   183  		if len(data)%32 != 0 {
   184  			return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
   185  		}
   186  		args = method.Outputs
   187  	}
   188  	if event, ok := abi.Events[name]; ok {
   189  		args = event.Inputs
   190  	}
   191  	if args == nil {
   192  		return nil, fmt.Errorf("abi: could not locate named method or event: %s", name)
   193  	}
   194  	return args, nil
   195  }
   196  
   197  // UnpackInput unpacks the input according to the ABI specification.
   198  func (abi ABI) UnpackInput(name string, data []byte) ([]interface{}, error) {
   199  	args, err := abi.getInputs(name, data)
   200  	if err != nil {
   201  		return nil, err
   202  	}
   203  	return args.Unpack(data)
   204  }
   205  
   206  // Unpack unpacks the output according to the abi specification.
   207  func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) {
   208  	args, err := abi.getArguments(name, data)
   209  	if err != nil {
   210  		return nil, err
   211  	}
   212  	return args.Unpack(data)
   213  }
   214  
   215  // UnpackInputIntoInterface unpacks the input in v according to the ABI specification.
   216  // It performs an additional copy. Please only use, if you want to unpack into a
   217  // structure that does not strictly conform to the ABI structure (e.g. has additional arguments)
   218  func (abi ABI) UnpackInputIntoInterface(v interface{}, name string, data []byte) error {
   219  	args, err := abi.getInputs(name, data)
   220  	if err != nil {
   221  		return err
   222  	}
   223  	unpacked, err := args.Unpack(data)
   224  	if err != nil {
   225  		return err
   226  	}
   227  	return args.Copy(v, unpacked)
   228  }
   229  
   230  // UnpackIntoInterface unpacks the output in v according to the abi specification.
   231  // It performs an additional copy. Please only use, if you want to unpack into a
   232  // structure that does not strictly conform to the abi structure (e.g. has additional arguments)
   233  func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error {
   234  	args, err := abi.getArguments(name, data)
   235  	if err != nil {
   236  		return err
   237  	}
   238  	unpacked, err := args.Unpack(data)
   239  	if err != nil {
   240  		return err
   241  	}
   242  	return args.Copy(v, unpacked)
   243  }
   244  
   245  // UnpackIntoMap unpacks a log into the provided map[string]interface{}.
   246  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
   247  	args, err := abi.getArguments(name, data)
   248  	if err != nil {
   249  		return err
   250  	}
   251  	return args.UnpackIntoMap(v, data)
   252  }
   253  
   254  // UnmarshalJSON implements json.Unmarshaler interface.
   255  func (abi *ABI) UnmarshalJSON(data []byte) error {
   256  	var fields []struct {
   257  		Type    string
   258  		Name    string
   259  		Inputs  []Argument
   260  		Outputs []Argument
   261  
   262  		// Status indicator which can be: "pure", "view",
   263  		// "nonpayable" or "payable".
   264  		StateMutability string
   265  
   266  		// Deprecated Status indicators, but removed in v0.6.0.
   267  		Constant bool // True if function is either pure or view
   268  		Payable  bool // True if function is payable
   269  
   270  		// Event relevant indicator represents the event is
   271  		// declared as anonymous.
   272  		Anonymous bool
   273  	}
   274  	if err := json.Unmarshal(data, &fields); err != nil {
   275  		return err
   276  	}
   277  	abi.Methods = make(map[string]Method)
   278  	abi.Events = make(map[string]Event)
   279  	abi.Errors = make(map[string]Error)
   280  	for _, field := range fields {
   281  		switch field.Type {
   282  		case "constructor":
   283  			abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil)
   284  		case "function":
   285  			name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Methods[s]; return ok })
   286  			abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs)
   287  		case "fallback":
   288  			// New introduced function type in v0.6.0, check more detail
   289  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   290  			if abi.HasFallback() {
   291  				return errors.New("only single fallback is allowed")
   292  			}
   293  			abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil)
   294  		case "receive":
   295  			// New introduced function type in v0.6.0, check more detail
   296  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   297  			if abi.HasReceive() {
   298  				return errors.New("only single receive is allowed")
   299  			}
   300  			if field.StateMutability != "payable" {
   301  				return errors.New("the statemutability of receive can only be payable")
   302  			}
   303  			abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil)
   304  		case "event":
   305  			name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Events[s]; return ok })
   306  			abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs)
   307  		case "error":
   308  			// Errors cannot be overloaded or overridden but are inherited,
   309  			// no need to resolve the name conflict here.
   310  			abi.Errors[field.Name] = NewError(field.Name, field.Inputs)
   311  		default:
   312  			return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name)
   313  		}
   314  	}
   315  	return nil
   316  }
   317  
   318  // MethodById looks up a method by the 4-byte id,
   319  // returns nil if none found.
   320  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   321  	if len(sigdata) < 4 {
   322  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   323  	}
   324  	for _, method := range abi.Methods {
   325  		if bytes.Equal(method.ID, sigdata[:4]) {
   326  			return &method, nil
   327  		}
   328  	}
   329  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   330  }
   331  
   332  // EventByID looks an event up by its topic hash in the
   333  // ABI and returns nil if none found.
   334  func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
   335  	for _, event := range abi.Events {
   336  		if bytes.Equal(event.ID.Bytes(), topic.Bytes()) {
   337  			return &event, nil
   338  		}
   339  	}
   340  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   341  }
   342  
   343  // HasFallback returns an indicator whether a fallback function is included.
   344  func (abi *ABI) HasFallback() bool {
   345  	return abi.Fallback.Type == Fallback
   346  }
   347  
   348  // HasReceive returns an indicator whether a receive function is included.
   349  func (abi *ABI) HasReceive() bool {
   350  	return abi.Receive.Type == Receive
   351  }
   352  
   353  // revertSelector is a special function selector for revert reason unpacking.
   354  var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
   355  
   356  // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
   357  // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
   358  // the provided revert reason is abi-encoded as if it were a call to a function
   359  // `Error(string)`. So it's a special tool for it.
   360  func UnpackRevert(data []byte) (string, error) {
   361  	if len(data) < 4 {
   362  		return "", errors.New("invalid data for unpacking")
   363  	}
   364  	if !bytes.Equal(data[:4], revertSelector) {
   365  		return "", errors.New("invalid data for unpacking")
   366  	}
   367  	typ, _ := NewType("string", "", nil)
   368  	unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
   369  	if err != nil {
   370  		return "", err
   371  	}
   372  	return unpacked[0].(string), nil
   373  }