natspec.go 6.2 KB

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