aboutsummaryrefslogtreecommitdiffstats
path: root/rpc/api/utils.go
blob: a620581404207172d439e7e054fde94f6524d8ff (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package api

import (
    "strings"

    "fmt"

    "github.com/ethereum/go-ethereum/eth"
    "github.com/ethereum/go-ethereum/rpc/codec"
    "github.com/ethereum/go-ethereum/xeth"
    "github.com/ethereum/go-ethereum/rpc/shared"
)

const (
    EthApiName = "eth"
)

// Parse a comma separated API string to individual api's
func ParseApiString(apistr string, codec codec.Codec, xeth *xeth.XEth, eth *eth.Ethereum) ([]EthereumApi, error) {
    if len(strings.TrimSpace(apistr)) == 0 {
        return nil, fmt.Errorf("Empty apistr provided")
    }

    names := strings.Split(apistr, ",")
    apis := make([]EthereumApi, len(names))

    for i, name := range names {
        switch strings.ToLower(strings.TrimSpace(name)) {
        case EthApiName:
            apis[i] = NewEthApi(xeth, codec)
        default:
            return nil, fmt.Errorf("Unknown API '%s'", name)
        }
    }

    return apis, nil
}

// combines multiple API's
type mergedApi struct {
    apis map[string]EthereumApi
}

// create new merged api instance
func newMergedApi(apis ...EthereumApi) *mergedApi {
    mergedApi := new(mergedApi)
    mergedApi.apis = make(map[string]EthereumApi)

    for _, api := range apis {
        for _, method := range api.Methods() {
            mergedApi.apis[method] = api
        }
    }
    return mergedApi
}

// Supported RPC methods
func (self *mergedApi) Methods() []string {
    all := make([]string, len(self.apis))
    for method, _ := range self.apis {
        all = append(all, method)
    }
    return all
}

// Call the correct API's Execute method for the given request
func (self *mergedApi) Execute(req *shared.Request) (interface{}, error) {
    if api, found := self.apis[req.Method]; found {
        return api.Execute(req)
    }
    return nil, shared.NewNotImplementedError(req.Method)
}

// Merge multiple API's to a single API instance
func Merge(apis ...EthereumApi) EthereumApi {
    return newMergedApi(apis...)
}