github.com/googgoog/go-ethereum@v1.9.7/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  	"fmt"
    23  	"io"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  )
    27  
    28  // The ABI holds information about a contract's context and available
    29  // invokable methods. It will allow you to type check function calls and
    30  // packs data accordingly.
    31  type ABI struct {
    32  	Constructor Method
    33  	Methods     map[string]Method
    34  	Events      map[string]Event
    35  }
    36  
    37  // JSON returns a parsed ABI interface and error if it failed.
    38  func JSON(reader io.Reader) (ABI, error) {
    39  	dec := json.NewDecoder(reader)
    40  
    41  	var abi ABI
    42  	if err := dec.Decode(&abi); err != nil {
    43  		return ABI{}, err
    44  	}
    45  
    46  	return abi, nil
    47  }
    48  
    49  // Pack the given method name to conform the ABI. Method call's data
    50  // will consist of method_id, args0, arg1, ... argN. Method id consists
    51  // of 4 bytes and arguments are all 32 bytes.
    52  // Method ids are created from the first 4 bytes of the hash of the
    53  // methods string signature. (signature = baz(uint32,string32))
    54  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    55  	// Fetch the ABI of the requested method
    56  	if name == "" {
    57  		// constructor
    58  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    59  		if err != nil {
    60  			return nil, err
    61  		}
    62  		return arguments, nil
    63  	}
    64  	method, exist := abi.Methods[name]
    65  	if !exist {
    66  		return nil, fmt.Errorf("method '%s' not found", name)
    67  	}
    68  	arguments, err := method.Inputs.Pack(args...)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	// Pack up the method ID too if not a constructor and return
    73  	return append(method.ID(), arguments...), nil
    74  }
    75  
    76  // Unpack output in v according to the abi specification
    77  func (abi ABI) Unpack(v interface{}, name string, data []byte) (err error) {
    78  	// since there can't be naming collisions with contracts and events,
    79  	// we need to decide whether we're calling a method or an event
    80  	if method, ok := abi.Methods[name]; ok {
    81  		if len(data)%32 != 0 {
    82  			return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
    83  		}
    84  		return method.Outputs.Unpack(v, data)
    85  	}
    86  	if event, ok := abi.Events[name]; ok {
    87  		return event.Inputs.Unpack(v, data)
    88  	}
    89  	return fmt.Errorf("abi: could not locate named method or event")
    90  }
    91  
    92  // UnpackIntoMap unpacks a log into the provided map[string]interface{}
    93  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
    94  	// since there can't be naming collisions with contracts and events,
    95  	// we need to decide whether we're calling a method or an event
    96  	if method, ok := abi.Methods[name]; ok {
    97  		if len(data)%32 != 0 {
    98  			return fmt.Errorf("abi: improperly formatted output")
    99  		}
   100  		return method.Outputs.UnpackIntoMap(v, data)
   101  	}
   102  	if event, ok := abi.Events[name]; ok {
   103  		return event.Inputs.UnpackIntoMap(v, data)
   104  	}
   105  	return fmt.Errorf("abi: could not locate named method or event")
   106  }
   107  
   108  // UnmarshalJSON implements json.Unmarshaler interface
   109  func (abi *ABI) UnmarshalJSON(data []byte) error {
   110  	var fields []struct {
   111  		Type      string
   112  		Name      string
   113  		Constant  bool
   114  		Anonymous bool
   115  		Inputs    []Argument
   116  		Outputs   []Argument
   117  	}
   118  	if err := json.Unmarshal(data, &fields); err != nil {
   119  		return err
   120  	}
   121  	abi.Methods = make(map[string]Method)
   122  	abi.Events = make(map[string]Event)
   123  	for _, field := range fields {
   124  		switch field.Type {
   125  		case "constructor":
   126  			abi.Constructor = Method{
   127  				Inputs: field.Inputs,
   128  			}
   129  		// empty defaults to function according to the abi spec
   130  		case "function", "":
   131  			name := field.Name
   132  			_, ok := abi.Methods[name]
   133  			for idx := 0; ok; idx++ {
   134  				name = fmt.Sprintf("%s%d", field.Name, idx)
   135  				_, ok = abi.Methods[name]
   136  			}
   137  			abi.Methods[name] = Method{
   138  				Name:    name,
   139  				RawName: field.Name,
   140  				Const:   field.Constant,
   141  				Inputs:  field.Inputs,
   142  				Outputs: field.Outputs,
   143  			}
   144  		case "event":
   145  			name := field.Name
   146  			_, ok := abi.Events[name]
   147  			for idx := 0; ok; idx++ {
   148  				name = fmt.Sprintf("%s%d", field.Name, idx)
   149  				_, ok = abi.Events[name]
   150  			}
   151  			abi.Events[name] = Event{
   152  				Name:      name,
   153  				RawName:   field.Name,
   154  				Anonymous: field.Anonymous,
   155  				Inputs:    field.Inputs,
   156  			}
   157  		}
   158  	}
   159  
   160  	return nil
   161  }
   162  
   163  // MethodById looks up a method by the 4-byte id
   164  // returns nil if none found
   165  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   166  	if len(sigdata) < 4 {
   167  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   168  	}
   169  	for _, method := range abi.Methods {
   170  		if bytes.Equal(method.ID(), sigdata[:4]) {
   171  			return &method, nil
   172  		}
   173  	}
   174  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   175  }
   176  
   177  // EventByID looks an event up by its topic hash in the
   178  // ABI and returns nil if none found.
   179  func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
   180  	for _, event := range abi.Events {
   181  		if bytes.Equal(event.ID().Bytes(), topic.Bytes()) {
   182  			return &event, nil
   183  		}
   184  	}
   185  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   186  }