utils.go 6.45 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

17
package rpc
18 19 20 21 22

import (
	"crypto/rand"
	"encoding/hex"
	"errors"
23
	"fmt"
24 25 26 27
	"math/big"
	"reflect"
	"unicode"
	"unicode/utf8"
28 29

	"golang.org/x/net/context"
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
)

// Is this an exported - upper case - name?
func isExported(name string) bool {
	rune, _ := utf8.DecodeRuneInString(name)
	return unicode.IsUpper(rune)
}

// Is this type exported or a builtin?
func isExportedOrBuiltinType(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	// PkgPath will be non-empty even for an exported type,
	// so we need to check the type name as well.
	return isExported(t.Name()) || t.PkgPath() == ""
}

48 49 50 51 52 53 54 55 56 57
var contextType = reflect.TypeOf((*context.Context)(nil)).Elem()

// isContextType returns an indication if the given t is of context.Context or *context.Context type
func isContextType(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	return t == contextType
}

58 59 60 61 62 63 64 65 66 67 68 69
var errorType = reflect.TypeOf((*error)(nil)).Elem()

// Implements this type the error interface
func isErrorType(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	return t.Implements(errorType)
}

var subscriptionType = reflect.TypeOf((*Subscription)(nil)).Elem()

70
// isSubscriptionType returns an indication if the given t is of Subscription or *Subscription type
71 72 73 74 75 76 77
func isSubscriptionType(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	return t == subscriptionType
}

78 79
// isPubSub tests whether the given method has as as first argument a context.Context
// and returns the pair (Subscription, error)
80
func isPubSub(methodType reflect.Type) bool {
81 82
	// numIn(0) is the receiver type
	if methodType.NumIn() < 2 || methodType.NumOut() != 2 {
83 84
		return false
	}
85 86 87 88

	return isContextType(methodType.In(1)) &&
		isSubscriptionType(methodType.Out(0)) &&
		isErrorType(methodType.Out(1))
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
}

// formatName will convert to first character to lower case
func formatName(name string) string {
	ret := []rune(name)
	if len(ret) > 0 {
		ret[0] = unicode.ToLower(ret[0])
	}
	return string(ret)
}

var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()

// Indication if this type should be serialized in hex
func isHexNum(t reflect.Type) bool {
	if t == nil {
		return false
	}
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	return t == bigIntType
}

var blockNumberType = reflect.TypeOf((*BlockNumber)(nil)).Elem()

// Indication if the given block is a BlockNumber
func isBlockNumber(t reflect.Type) bool {
	if t == nil {
		return false
	}

	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	return t == blockNumberType
}

// suitableCallbacks iterates over the methods of the given type. It will determine if a method satisfies the criteria
// for a RPC callback or a subscription callback and adds it to the collection of callbacks or subscriptions. See server
// documentation for a summary of these criteria.
func suitableCallbacks(rcvr reflect.Value, typ reflect.Type) (callbacks, subscriptions) {
	callbacks := make(callbacks)
	subscriptions := make(subscriptions)

METHODS:
	for m := 0; m < typ.NumMethod(); m++ {
		method := typ.Method(m)
		mtype := method.Type
		mname := formatName(method.Name)
		if method.PkgPath != "" { // method must be exported
			continue
		}

		var h callback
		h.isSubscribe = isPubSub(mtype)
		h.rcvr = rcvr
		h.method = method
		h.errPos = -1

151 152 153 154 155 156 157
		firstArg := 1
		numIn := mtype.NumIn()
		if numIn >= 2 && mtype.In(1) == contextType {
			h.hasCtx = true
			firstArg = 2
		}

158
		if h.isSubscribe {
159 160
			h.argTypes = make([]reflect.Type, numIn-firstArg) // skip rcvr type
			for i := firstArg; i < numIn; i++ {
161 162
				argType := mtype.In(i)
				if isExportedOrBuiltinType(argType) {
163
					h.argTypes[i-firstArg] = argType
164 165 166 167 168 169 170 171 172 173 174
				} else {
					continue METHODS
				}
			}

			subscriptions[mname] = &h
			continue METHODS
		}

		// determine method arguments, ignore first arg since it's the receiver type
		// Arguments must be exported or builtin types
175 176
		h.argTypes = make([]reflect.Type, numIn-firstArg)
		for i := firstArg; i < numIn; i++ {
177 178 179 180
			argType := mtype.In(i)
			if !isExportedOrBuiltinType(argType) {
				continue METHODS
			}
181
			h.argTypes[i-firstArg] = argType
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		}

		// check that all returned values are exported or builtin types
		for i := 0; i < mtype.NumOut(); i++ {
			if !isExportedOrBuiltinType(mtype.Out(i)) {
				continue METHODS
			}
		}

		// when a method returns an error it must be the last returned value
		h.errPos = -1
		for i := 0; i < mtype.NumOut(); i++ {
			if isErrorType(mtype.Out(i)) {
				h.errPos = i
				break
			}
		}

		if h.errPos >= 0 && h.errPos != mtype.NumOut()-1 {
			continue METHODS
		}

		switch mtype.NumOut() {
		case 0, 1:
			break
		case 2:
			if h.errPos == -1 { // method must one return value and 1 error
				continue METHODS
			}
			break
		default:
			continue METHODS
		}

		callbacks[mname] = &h
	}

	return callbacks, subscriptions
}

222
func newSubscriptionID() (string, error) {
223 224 225 226 227 228 229
	var subid [16]byte
	n, _ := rand.Read(subid[:])
	if n != 16 {
		return "", errors.New("Unable to generate subscription id")
	}
	return "0x" + hex.EncodeToString(subid[:]), nil
}
230 231 232 233

// SupportedModules returns the collection of API's that the RPC server offers
// on which the given client connects.
func SupportedModules(client Client) (map[string]string, error) {
234
	req := JSONRequest{
235
		Id:      []byte("1"),
236
		Version: "2.0",
237
		Method:  MetadataApi + "_modules",
238 239 240 241 242
	}
	if err := client.Send(req); err != nil {
		return nil, err
	}

243
	var response JSONSuccessResponse
244 245 246
	if err := client.Recv(&response); err != nil {
		return nil, err
	}
247
	if response.Result != nil {
248
		mods := make(map[string]string)
249
		if modules, ok := response.Result.(map[string]interface{}); ok {
250 251 252 253 254 255 256 257
			for m, v := range modules {
				mods[m] = fmt.Sprintf("%s", v)
			}
			return mods, nil
		}
	}
	return nil, fmt.Errorf("unable to retrieve modules")
}