github.com/benorgera/go-ethereum@v1.10.18-0.20220401011646-b3f57b1a73ba/accounts/abi/abi.go (about)

     1  // Copyright 2015 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 abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  )
    29  
    30  // The ABI holds information about a contract's context and available
    31  // invokable methods. It will allow you to type check function calls and
    32  // packs data accordingly.
    33  type ABI struct {
    34  	Constructor Method
    35  	Methods     map[string]Method
    36  	Events      map[string]Event
    37  	Errors      map[string]Error
    38  
    39  	// Additional "special" functions introduced in solidity v0.6.0.
    40  	// It's separated from the original default fallback. Each contract
    41  	// can only define one fallback and receive function.
    42  	Fallback Method // Note it's also used to represent legacy fallback before v0.6.0
    43  	Receive  Method
    44  }
    45  
    46  // JSON returns a parsed ABI interface and error if it failed.
    47  func JSON(reader io.Reader) (ABI, error) {
    48  	dec := json.NewDecoder(reader)
    49  
    50  	var abi ABI
    51  	if err := dec.Decode(&abi); err != nil {
    52  		return ABI{}, err
    53  	}
    54  	return abi, nil
    55  }
    56  
    57  // Pack the given method name to conform the ABI. Method call's data
    58  // will consist of method_id, args0, arg1, ... argN. Method id consists
    59  // of 4 bytes and arguments are all 32 bytes.
    60  // Method ids are created from the first 4 bytes of the hash of the
    61  // methods string signature. (signature = baz(uint32,string32))
    62  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    63  	// Fetch the ABI of the requested method
    64  	if name == "" {
    65  		// constructor
    66  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    67  		if err != nil {
    68  			return nil, err
    69  		}
    70  		return arguments, nil
    71  	}
    72  	method, exist := abi.Methods[name]
    73  	if !exist {
    74  		return nil, fmt.Errorf("method '%s' not found", name)
    75  	}
    76  	arguments, err := method.Inputs.Pack(args...)
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  	// Pack up the method ID too if not a constructor and return
    81  	return append(method.ID, arguments...), nil
    82  }
    83  
    84  func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
    85  	// since there can't be naming collisions with contracts and events,
    86  	// we need to decide whether we're calling a method or an event
    87  	var args Arguments
    88  	if method, ok := abi.Methods[name]; ok {
    89  		if len(data)%32 != 0 {
    90  			return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
    91  		}
    92  		args = method.Outputs
    93  	}
    94  	if event, ok := abi.Events[name]; ok {
    95  		args = event.Inputs
    96  	}
    97  	if args == nil {
    98  		return nil, errors.New("abi: could not locate named method or event")
    99  	}
   100  	return args, nil
   101  }
   102  
   103  // Unpack unpacks the output according to the abi specification.
   104  func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) {
   105  	args, err := abi.getArguments(name, data)
   106  	if err != nil {
   107  		return nil, err
   108  	}
   109  	return args.Unpack(data)
   110  }
   111  
   112  // UnpackIntoInterface unpacks the output in v according to the abi specification.
   113  // It performs an additional copy. Please only use, if you want to unpack into a
   114  // structure that does not strictly conform to the abi structure (e.g. has additional arguments)
   115  func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error {
   116  	args, err := abi.getArguments(name, data)
   117  	if err != nil {
   118  		return err
   119  	}
   120  	unpacked, err := args.Unpack(data)
   121  	if err != nil {
   122  		return err
   123  	}
   124  	return args.Copy(v, unpacked)
   125  }
   126  
   127  // UnpackIntoMap unpacks a log into the provided map[string]interface{}.
   128  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
   129  	args, err := abi.getArguments(name, data)
   130  	if err != nil {
   131  		return err
   132  	}
   133  	return args.UnpackIntoMap(v, data)
   134  }
   135  
   136  // UnmarshalJSON implements json.Unmarshaler interface.
   137  func (abi *ABI) UnmarshalJSON(data []byte) error {
   138  	var fields []struct {
   139  		Type    string
   140  		Name    string
   141  		Inputs  []Argument
   142  		Outputs []Argument
   143  
   144  		// Status indicator which can be: "pure", "view",
   145  		// "nonpayable" or "payable".
   146  		StateMutability string
   147  
   148  		// Deprecated Status indicators, but removed in v0.6.0.
   149  		Constant bool // True if function is either pure or view
   150  		Payable  bool // True if function is payable
   151  
   152  		// Event relevant indicator represents the event is
   153  		// declared as anonymous.
   154  		Anonymous bool
   155  	}
   156  	if err := json.Unmarshal(data, &fields); err != nil {
   157  		return err
   158  	}
   159  	abi.Methods = make(map[string]Method)
   160  	abi.Events = make(map[string]Event)
   161  	abi.Errors = make(map[string]Error)
   162  	for _, field := range fields {
   163  		switch field.Type {
   164  		case "constructor":
   165  			abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil)
   166  		case "function":
   167  			name := overloadedName(field.Name, func(s string) bool { _, ok := abi.Methods[s]; return ok })
   168  			abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs)
   169  		case "fallback":
   170  			// New introduced function type in v0.6.0, check more detail
   171  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   172  			if abi.HasFallback() {
   173  				return errors.New("only single fallback is allowed")
   174  			}
   175  			abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil)
   176  		case "receive":
   177  			// New introduced function type in v0.6.0, check more detail
   178  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   179  			if abi.HasReceive() {
   180  				return errors.New("only single receive is allowed")
   181  			}
   182  			if field.StateMutability != "payable" {
   183  				return errors.New("the statemutability of receive can only be payable")
   184  			}
   185  			abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil)
   186  		case "event":
   187  			name := overloadedName(field.Name, func(s string) bool { _, ok := abi.Events[s]; return ok })
   188  			abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs)
   189  		case "error":
   190  			abi.Errors[field.Name] = NewError(field.Name, field.Inputs)
   191  		default:
   192  			return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name)
   193  		}
   194  	}
   195  	return nil
   196  }
   197  
   198  // MethodById looks up a method by the 4-byte id,
   199  // returns nil if none found.
   200  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   201  	if len(sigdata) < 4 {
   202  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   203  	}
   204  	for _, method := range abi.Methods {
   205  		if bytes.Equal(method.ID, sigdata[:4]) {
   206  			return &method, nil
   207  		}
   208  	}
   209  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   210  }
   211  
   212  // EventByID looks an event up by its topic hash in the
   213  // ABI and returns nil if none found.
   214  func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
   215  	for _, event := range abi.Events {
   216  		if bytes.Equal(event.ID.Bytes(), topic.Bytes()) {
   217  			return &event, nil
   218  		}
   219  	}
   220  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   221  }
   222  
   223  // HasFallback returns an indicator whether a fallback function is included.
   224  func (abi *ABI) HasFallback() bool {
   225  	return abi.Fallback.Type == Fallback
   226  }
   227  
   228  // HasReceive returns an indicator whether a receive function is included.
   229  func (abi *ABI) HasReceive() bool {
   230  	return abi.Receive.Type == Receive
   231  }
   232  
   233  // revertSelector is a special function selector for revert reason unpacking.
   234  var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
   235  
   236  // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
   237  // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
   238  // the provided revert reason is abi-encoded as if it were a call to a function
   239  // `Error(string)`. So it's a special tool for it.
   240  func UnpackRevert(data []byte) (string, error) {
   241  	if len(data) < 4 {
   242  		return "", errors.New("invalid data for unpacking")
   243  	}
   244  	if !bytes.Equal(data[:4], revertSelector) {
   245  		return "", errors.New("invalid data for unpacking")
   246  	}
   247  	typ, _ := NewType("string", "", nil)
   248  	unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
   249  	if err != nil {
   250  		return "", err
   251  	}
   252  	return unpacked[0].(string), nil
   253  }
   254  
   255  // overloadedName returns the next available name for a given thing.
   256  // Needed since solidity allows for overloading.
   257  //
   258  // e.g. if the abi contains Methods send, send1
   259  // overloadedName would return send2 for input send.
   260  //
   261  // overloadedName works for methods, events and errors.
   262  func overloadedName(rawName string, isAvail func(string) bool) string {
   263  	name := rawName
   264  	ok := isAvail(name)
   265  	for idx := 0; ok; idx++ {
   266  		name = fmt.Sprintf("%s%d", rawName, idx)
   267  		ok = isAvail(name)
   268  	}
   269  	return name
   270  }