aboutsummaryrefslogtreecommitdiffstats
path: root/common/natspec/natspec.go
blob: ceac3f5d364a70cffe3440f92805c2ff37d6d2f6 (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
78
79
80
81
82
83
84
85
86
87
88
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package natspec

import (
    "bytes"
    "encoding/json"
    "fmt"
    "github.com/robertkrimen/otto"
    "strings"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/common/docserver"
    "github.com/ethereum/go-ethereum/common/resolver"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/xeth"
)

type abi2method map[[8]byte]*method

type NatSpec struct {
    jsvm                    *otto.Otto
    userDocJson, abiDocJson []byte
    userDoc                 userDoc
    tx, data                string
    // abiDoc abiDoc
}

func getFallbackNotice(comment, tx string) string {

    return "About to submit transaction (" + comment + "): " + tx

}

func GetNotice(xeth *xeth.XEth, tx string, http *docserver.DocServer) (notice string) {

    ns, err := New(xeth, tx, http)
    if err != nil {
        if ns == nil {
            return getFallbackNotice("no NatSpec info found for contract", tx)
        } else {
            return getFallbackNotice("invalid NatSpec info", tx)
        }
    }

    notice, err2 := ns.Notice()

    if err2 != nil {
        return getFallbackNotice("couldn't create NatSpec notice", tx)
    }

    return

}

func New(xeth *xeth.XEth, tx string, http *docserver.DocServer) (self *NatSpec, err error) {

    // extract contract address from tx

    var obj map[string]json.RawMessage
    err = json.Unmarshal([]byte(tx), &obj)
    if err != nil {
        return
    }
    var tmp []map[string]string
    err = json.Unmarshal(obj["params"], &tmp)
    if err != nil {
        return
    }
    contractAddress := tmp[0]["to"]

    // retrieve contract hash from state
    if !xeth.IsContract(contractAddress) {
        err = fmt.Errorf("NatSpec error: contract not found")
        return
    }
    codehex := xeth.CodeAt(contractAddress)
    codeHash := common.BytesToHash(crypto.Sha3(common.Hex2Bytes(codehex[2:])))
    // parse out host/domain

    // set up nameresolver with natspecreg + urlhint contract addresses
    res := resolver.New(
        xeth,
        resolver.URLHintContractAddress,
        resolver.HashRegContractAddress,
    )

    // resolve host via HashReg/UrlHint Resolver
    uri, hash, err := res.KeyToUrl(codeHash)
    if err != nil {
        return
    }

    // get content via http client and authenticate content using hash
    content, err := http.GetAuthContent(uri, hash)
    if err != nil {
        return
    }

    // get abi, userdoc
    var obj2 map[string]json.RawMessage
    err = json.Unmarshal(content, &obj2)
    if err != nil {
        return
    }

    abi := []byte(obj2["abi"])
    userdoc := []byte(obj2["userdoc"])

    self, err = NewWithDocs(abi, userdoc, tx)
    return
}

func NewWithDocs(abiDocJson, userDocJson []byte, tx string) (self *NatSpec, err error) {

    var obj map[string]json.RawMessage
    err = json.Unmarshal([]byte(tx), &obj)
    if err != nil {
        return
    }
    var tmp []map[string]string
    err = json.Unmarshal(obj["params"], &tmp)
    if err != nil {
        return
    }
    data := tmp[0]["data"]

    self = &NatSpec{
        jsvm:        otto.New(),
        abiDocJson:  abiDocJson,
        userDocJson: userDocJson,
        tx:          tx,
        data:        data,
    }

    // load and require natspec js (but it is meant to be protected environment)
    _, err = self.jsvm.Run(natspecJS)
    if err != nil {
        return
    }
    _, err = self.jsvm.Run("var natspec = require('natspec');")
    if err != nil {
        return
    }

    err = json.Unmarshal(userDocJson, &self.userDoc)
    // err = parseAbiJson(abiDocJson, &self.abiDoc)

    return
}

// type abiDoc []method

// type method struct {
//  Name   string  `json:name`
//  Inputs []input `json:inputs`
//  abiKey [8]byte
// }

// type input struct {
//  Name string `json:name`
//  Type string `json:type`
// }

// json skeleton for abi doc (contract method definitions)
type method struct {
    Notice string `json:notice`
    name   string
}

type userDoc struct {
    Methods map[string]*method `json:methods`
}

func (self *NatSpec) makeAbi2method(abiKey [8]byte) (meth *method) {
    for signature, m := range self.userDoc.Methods {
        name := strings.Split(signature, "(")[0]
        hash := []byte(common.Bytes2Hex(crypto.Sha3([]byte(signature))))
        var key [8]byte
        copy(key[:], hash[:8])
        if bytes.Equal(key[:], abiKey[:]) {
            meth = m
            meth.name = name
            return
        }
    }
    return
}

func (self *NatSpec) Notice() (notice string, err error) {
    var abiKey [8]byte
    if len(self.data) < 10 {
        err = fmt.Errorf("Invalid transaction data")
        return
    }
    copy(abiKey[:], self.data[2:10])
    meth := self.makeAbi2method(abiKey)

    if meth == nil {
        err = fmt.Errorf("abi key %x does not match any method %v")
        return
    }
    notice, err = self.noticeForMethod(self.tx, meth.name, meth.Notice)
    return
}

func (self *NatSpec) noticeForMethod(tx string, name, expression string) (notice string, err error) {

    if _, err = self.jsvm.Run("var transaction = " + tx + ";"); err != nil {
        return "", fmt.Errorf("natspec.js error setting transaction: %v", err)
    }

    if _, err = self.jsvm.Run("var abi = " + string(self.abiDocJson) + ";"); err != nil {
        return "", fmt.Errorf("natspec.js error setting abi: %v", err)
    }

    if _, err = self.jsvm.Run("var method = '" + name + "';"); err != nil {
        return "", fmt.Errorf("natspec.js error setting method: %v", err)
    }

    if _, err = self.jsvm.Run("var expression = \"" + expression + "\";"); err != nil {
        return "", fmt.Errorf("natspec.js error setting expression: %v", err)
    }

    self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};")
    value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);")
    if err != nil {
        return "", fmt.Errorf("natspec.js error evaluating expression: %v", err)
    }
    evalError := "Natspec evaluation failed, wrong input params"
    if value.String() == evalError {
        return "", fmt.Errorf("natspec.js error evaluating expression: wrong input params in expression '%s'", expression)
    }
    if len(value.String()) == 0 {
        return "", fmt.Errorf("natspec.js error evaluating expression")
    }

    return value.String(), nil

}