github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/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  	"encoding/json"
    21  	"fmt"
    22  	"io"
    23  	"reflect"
    24  	"strings"
    25  
    26  	"github.com/wanchain/go-wanchain/common"
    27  )
    28  
    29  // The ABI holds information about a contract's context and available
    30  // invokable methods. It will allow you to type check function calls and
    31  // packs data accordingly.
    32  type ABI struct {
    33  	Constructor Method
    34  	Methods     map[string]Method
    35  	Events      map[string]Event
    36  }
    37  
    38  // JSON returns a parsed ABI interface and error if it failed.
    39  func JSON(reader io.Reader) (ABI, error) {
    40  	dec := json.NewDecoder(reader)
    41  
    42  	var abi ABI
    43  	if err := dec.Decode(&abi); err != nil {
    44  		return ABI{}, err
    45  	}
    46  
    47  	return abi, nil
    48  }
    49  
    50  // Pack the given method name to conform the ABI. Method call's data
    51  // will consist of method_id, args0, arg1, ... argN. Method id consists
    52  // of 4 bytes and arguments are all 32 bytes.
    53  // Method ids are created from the first 4 bytes of the hash of the
    54  // methods string signature. (signature = baz(uint32,string32))
    55  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    56  	// Fetch the ABI of the requested method
    57  	var method Method
    58  
    59  	if name == "" {
    60  		method = abi.Constructor
    61  	} else {
    62  		m, exist := abi.Methods[name]
    63  		if !exist {
    64  			return nil, fmt.Errorf("method '%s' not found", name)
    65  		}
    66  		method = m
    67  	}
    68  	arguments, err := method.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  	if name == "" {
    74  		return arguments, nil
    75  	}
    76  	return append(method.Id(), arguments...), nil
    77  }
    78  
    79  // these variable are used to determine certain types during type assertion for
    80  // assignment.
    81  var (
    82  	r_interSlice = reflect.TypeOf([]interface{}{})
    83  	r_hash       = reflect.TypeOf(common.Hash{})
    84  	r_bytes      = reflect.TypeOf([]byte{})
    85  	r_byte       = reflect.TypeOf(byte(0))
    86  )
    87  
    88  // Unpack output in v according to the abi specification
    89  func (abi ABI) Unpack(v interface{}, name string, output []byte) (errRet error) {
    90  	var method = abi.Methods[name]
    91  	errRet = nil
    92  
    93  	defer func(){
    94  		if r := recover(); r != nil {
    95  			errRet = fmt.Errorf("abi Unpack panic unexpected!")
    96  		}
    97  	}()
    98  
    99  
   100  	if len(output) == 0 {
   101  		errRet = fmt.Errorf("abi: unmarshalling empty output")
   102  		return
   103  	}
   104  
   105  	// make sure the passed value is a pointer
   106  	valueOf := reflect.ValueOf(v)
   107  	if reflect.Ptr != valueOf.Kind() {
   108  		errRet = fmt.Errorf("abi: Unpack(non-pointer %T)", v)
   109  		return
   110  	}
   111  
   112  	var (
   113  		value = valueOf.Elem()
   114  		typ   = value.Type()
   115  	)
   116  
   117  	if len(method.Outputs) > 1 {
   118  		switch value.Kind() {
   119  		// struct will match named return values to the struct's field
   120  		// names
   121  		case reflect.Struct:
   122  			for i := 0; i < len(method.Outputs); i++ {
   123  				marshalledValue, err := toGoType(i, method.Outputs[i], output)
   124  				if err != nil {
   125  					errRet = err
   126  					return
   127  				}
   128  				reflectValue := reflect.ValueOf(marshalledValue)
   129  
   130  				for j := 0; j < typ.NumField(); j++ {
   131  					field := typ.Field(j)
   132  					// TODO read tags: `abi:"fieldName"`
   133  					if field.Name == strings.ToUpper(method.Outputs[i].Name[:1])+method.Outputs[i].Name[1:] {
   134  						if err := set(value.Field(j), reflectValue, method.Outputs[i]); err != nil {
   135  							errRet = err
   136  							return
   137  						}
   138  					}
   139  				}
   140  			}
   141  		case reflect.Slice:
   142  			if !value.Type().AssignableTo(r_interSlice) {
   143  				errRet = fmt.Errorf("abi: cannot marshal tuple in to slice %T (only []interface{} is supported)", v)
   144  				return
   145  			}
   146  
   147  			// if the slice already contains values, set those instead of the interface slice itself.
   148  			if value.Len() > 0 {
   149  				if len(method.Outputs) > value.Len() {
   150  					errRet = fmt.Errorf("abi: cannot marshal in to slices of unequal size (require: %v, got: %v)", len(method.Outputs), value.Len())
   151  					return
   152  				}
   153  
   154  				for i := 0; i < len(method.Outputs); i++ {
   155  					marshalledValue, err := toGoType(i, method.Outputs[i], output)
   156  					if err != nil {
   157  						errRet = err
   158  						return
   159  					}
   160  					reflectValue := reflect.ValueOf(marshalledValue)
   161  					if err := set(value.Index(i).Elem(), reflectValue, method.Outputs[i]); err != nil {
   162  						errRet = err
   163  						return
   164  					}
   165  				}
   166  				return
   167  			}
   168  
   169  			// create a new slice and start appending the unmarshalled
   170  			// values to the new interface slice.
   171  			z := reflect.MakeSlice(typ, 0, len(method.Outputs))
   172  			for i := 0; i < len(method.Outputs); i++ {
   173  				marshalledValue, err := toGoType(i, method.Outputs[i], output)
   174  				if err != nil {
   175  					errRet = err
   176  					return
   177  				}
   178  				z = reflect.Append(z, reflect.ValueOf(marshalledValue))
   179  			}
   180  			value.Set(z)
   181  		default:
   182  			errRet = fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
   183  			return
   184  		}
   185  
   186  	} else {
   187  		marshalledValue, err := toGoType(0, method.Outputs[0], output)
   188  		if err != nil {
   189  			errRet = err
   190  			return
   191  		}
   192  		if err := set(value, reflect.ValueOf(marshalledValue), method.Outputs[0]); err != nil {
   193  			errRet = err
   194  			return
   195  		}
   196  	}
   197  
   198  	return
   199  }
   200  
   201  func (abi *ABI) UnmarshalJSON(data []byte) error {
   202  	var fields []struct {
   203  		Type      string
   204  		Name      string
   205  		Constant  bool
   206  		Indexed   bool
   207  		Anonymous bool
   208  		Inputs    []Argument
   209  		Outputs   []Argument
   210  	}
   211  
   212  	if err := json.Unmarshal(data, &fields); err != nil {
   213  		return err
   214  	}
   215  
   216  	abi.Methods = make(map[string]Method)
   217  	abi.Events = make(map[string]Event)
   218  	for _, field := range fields {
   219  		switch field.Type {
   220  		case "constructor":
   221  			abi.Constructor = Method{
   222  				Inputs: field.Inputs,
   223  			}
   224  		// empty defaults to function according to the abi spec
   225  		case "function", "":
   226  			abi.Methods[field.Name] = Method{
   227  				Name:    field.Name,
   228  				Const:   field.Constant,
   229  				Inputs:  field.Inputs,
   230  				Outputs: field.Outputs,
   231  			}
   232  		case "event":
   233  			abi.Events[field.Name] = Event{
   234  				Name:      field.Name,
   235  				Anonymous: field.Anonymous,
   236  				Inputs:    field.Inputs,
   237  			}
   238  		}
   239  	}
   240  
   241  	return nil
   242  }