natspec.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package natspec
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "github.com/robertkrimen/otto"
  22. "strings"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/docserver"
  25. "github.com/ethereum/go-ethereum/common/registrar"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/xeth"
  28. )
  29. type abi2method map[[8]byte]*method
  30. type NatSpec struct {
  31. jsvm *otto.Otto
  32. abiDocJson []byte
  33. userDoc userDoc
  34. tx, data string
  35. }
  36. // main entry point for to get natspec notice for a transaction
  37. // the implementation is frontend friendly in that it always gives back
  38. // a notice that is safe to display
  39. // :FIXME: the second return value is an error, which can be used to fine-tune bahaviour
  40. func GetNotice(xeth *xeth.XEth, tx string, http *docserver.DocServer) (notice string) {
  41. ns, err := New(xeth, tx, http)
  42. if err != nil {
  43. if ns == nil {
  44. return getFallbackNotice(fmt.Sprintf("no NatSpec info found for contract: %v", err), tx)
  45. } else {
  46. return getFallbackNotice(fmt.Sprintf("invalid NatSpec info: %v", err), tx)
  47. }
  48. }
  49. notice, err = ns.Notice()
  50. if err != nil {
  51. return getFallbackNotice(fmt.Sprintf("NatSpec notice error: %v", err), tx)
  52. }
  53. return
  54. }
  55. func getFallbackNotice(comment, tx string) string {
  56. return fmt.Sprintf("About to submit transaction (%s): %s", comment, tx)
  57. }
  58. type transaction struct {
  59. To string `json:"to"`
  60. Data string `json:"data"`
  61. }
  62. type jsonTx struct {
  63. Params []transaction `json:"params"`
  64. }
  65. type contractInfo struct {
  66. Source string `json:"source"`
  67. Language string `json:"language"`
  68. Version string `json:"compilerVersion"`
  69. AbiDefinition json.RawMessage `json:"abiDefinition"`
  70. UserDoc userDoc `json:"userDoc"`
  71. DeveloperDoc json.RawMessage `json:"developerDoc"`
  72. }
  73. func New(xeth *xeth.XEth, jsontx string, http *docserver.DocServer) (self *NatSpec, err error) {
  74. // extract contract address from tx
  75. var tx jsonTx
  76. err = json.Unmarshal([]byte(jsontx), &tx)
  77. if err != nil {
  78. return
  79. }
  80. t := tx.Params[0]
  81. contractAddress := t.To
  82. content, err := FetchDocsForContract(contractAddress, xeth, http)
  83. if err != nil {
  84. return
  85. }
  86. self, err = NewWithDocs(content, jsontx, t.Data)
  87. return
  88. }
  89. // also called by admin.contractInfo.get
  90. func FetchDocsForContract(contractAddress string, xeth *xeth.XEth, ds *docserver.DocServer) (content []byte, err error) {
  91. // retrieve contract hash from state
  92. codehex := xeth.CodeAt(contractAddress)
  93. codeb := xeth.CodeAtBytes(contractAddress)
  94. if codehex == "0x" {
  95. err = fmt.Errorf("contract (%v) not found", contractAddress)
  96. return
  97. }
  98. codehash := common.BytesToHash(crypto.Sha3(codeb))
  99. // set up nameresolver with natspecreg + urlhint contract addresses
  100. reg := registrar.New(xeth)
  101. // resolve host via HashReg/UrlHint Resolver
  102. hash, err := reg.HashToHash(codehash)
  103. if err != nil {
  104. return
  105. }
  106. if ds.HasScheme("bzz") {
  107. content, err = ds.Get("bzz://"+hash.Hex()[2:], "")
  108. if err == nil { // non-fatal
  109. return
  110. }
  111. err = nil
  112. //falling back to urlhint
  113. }
  114. uri, err := reg.HashToUrl(hash)
  115. if err != nil {
  116. return
  117. }
  118. // get content via http client and authenticate content using hash
  119. content, err = ds.GetAuthContent(uri, hash)
  120. if err != nil {
  121. return
  122. }
  123. return
  124. }
  125. func NewWithDocs(infoDoc []byte, tx string, data string) (self *NatSpec, err error) {
  126. var contract contractInfo
  127. err = json.Unmarshal(infoDoc, &contract)
  128. if err != nil {
  129. return
  130. }
  131. self = &NatSpec{
  132. jsvm: otto.New(),
  133. abiDocJson: []byte(contract.AbiDefinition),
  134. userDoc: contract.UserDoc,
  135. tx: tx,
  136. data: data,
  137. }
  138. // load and require natspec js (but it is meant to be protected environment)
  139. _, err = self.jsvm.Run(natspecJS)
  140. if err != nil {
  141. return
  142. }
  143. _, err = self.jsvm.Run("var natspec = require('natspec');")
  144. return
  145. }
  146. // type abiDoc []method
  147. // type method struct {
  148. // Name string `json:name`
  149. // Inputs []input `json:inputs`
  150. // abiKey [8]byte
  151. // }
  152. // type input struct {
  153. // Name string `json:name`
  154. // Type string `json:type`
  155. // }
  156. // json skeleton for abi doc (contract method definitions)
  157. type method struct {
  158. Notice string `json:notice`
  159. name string
  160. }
  161. type userDoc struct {
  162. Methods map[string]*method `json:methods`
  163. }
  164. func (self *NatSpec) makeAbi2method(abiKey [8]byte) (meth *method) {
  165. for signature, m := range self.userDoc.Methods {
  166. name := strings.Split(signature, "(")[0]
  167. hash := []byte(common.Bytes2Hex(crypto.Sha3([]byte(signature))))
  168. var key [8]byte
  169. copy(key[:], hash[:8])
  170. if bytes.Equal(key[:], abiKey[:]) {
  171. meth = m
  172. meth.name = name
  173. return
  174. }
  175. }
  176. return
  177. }
  178. func (self *NatSpec) Notice() (notice string, err error) {
  179. var abiKey [8]byte
  180. if len(self.data) < 10 {
  181. err = fmt.Errorf("Invalid transaction data")
  182. return
  183. }
  184. copy(abiKey[:], self.data[2:10])
  185. meth := self.makeAbi2method(abiKey)
  186. if meth == nil {
  187. err = fmt.Errorf("abi key does not match any method")
  188. return
  189. }
  190. notice, err = self.noticeForMethod(self.tx, meth.name, meth.Notice)
  191. return
  192. }
  193. func (self *NatSpec) noticeForMethod(tx string, name, expression string) (notice string, err error) {
  194. if _, err = self.jsvm.Run("var transaction = " + tx + ";"); err != nil {
  195. return "", fmt.Errorf("natspec.js error setting transaction: %v", err)
  196. }
  197. if _, err = self.jsvm.Run("var abi = " + string(self.abiDocJson) + ";"); err != nil {
  198. return "", fmt.Errorf("natspec.js error setting abi: %v", err)
  199. }
  200. if _, err = self.jsvm.Run("var method = '" + name + "';"); err != nil {
  201. return "", fmt.Errorf("natspec.js error setting method: %v", err)
  202. }
  203. if _, err = self.jsvm.Run("var expression = \"" + expression + "\";"); err != nil {
  204. return "", fmt.Errorf("natspec.js error setting expression: %v", err)
  205. }
  206. self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};")
  207. value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);")
  208. if err != nil {
  209. return "", fmt.Errorf("natspec.js error evaluating expression: %v", err)
  210. }
  211. evalError := "Natspec evaluation failed, wrong input params"
  212. if value.String() == evalError {
  213. return "", fmt.Errorf("natspec.js error evaluating expression: wrong input params in expression '%s'", expression)
  214. }
  215. if len(value.String()) == 0 {
  216. return "", fmt.Errorf("natspec.js error evaluating expression")
  217. }
  218. return value.String(), nil
  219. }