natspec_e2e_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  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. // The go-ethereum library 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package natspec
  17. import (
  18. "fmt"
  19. "io/ioutil"
  20. "math/big"
  21. "os"
  22. "runtime"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/docserver"
  29. "github.com/ethereum/go-ethereum/common/registrar"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/eth"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. xe "github.com/ethereum/go-ethereum/xeth"
  35. )
  36. const (
  37. testBalance = "10000000000000000000"
  38. testFileName = "long_file_name_for_testing_registration_of_URLs_longer_than_32_bytes.content"
  39. testNotice = "Register key `utils.toHex(_key)` <- content `utils.toHex(_content)`"
  40. testExpNotice = "Register key 0xadd1a7d961cff0242089674ec2ef6fca671ab15e1fe80e38859fc815b98d88ab <- content 0xb3a2dea218de5d8bbe6c4645aadbf67b5ab00ecb1a9ec95dbdad6a0eed3e41a7"
  41. testExpNotice2 = `About to submit transaction (NatSpec notice error: abi key does not match any method): {"params":[{"to":"%s","data": "0x31e12c20"}]}`
  42. testExpNotice3 = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x1392c62d05b2d149e22a339c531157ae06b44d39a674cce500064b12b9aeb019'): {"params":[{"to":"%s","data": "0x300a3bbfb3a2dea218de5d8bbe6c4645aadbf67b5ab00ecb1a9ec95dbdad6a0eed3e41a7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000066696c653a2f2f2f746573742e636f6e74656e74"}]}`
  43. )
  44. const (
  45. testUserDoc = `
  46. {
  47. "methods": {
  48. "register(uint256,uint256)": {
  49. "notice": "` + testNotice + `"
  50. }
  51. },
  52. "invariants": [
  53. { "notice": "" }
  54. ],
  55. "construction": [
  56. { "notice": "" }
  57. ]
  58. }
  59. `
  60. testAbiDefinition = `
  61. [{
  62. "name": "register",
  63. "constant": false,
  64. "type": "function",
  65. "inputs": [{
  66. "name": "_key",
  67. "type": "uint256"
  68. }, {
  69. "name": "_content",
  70. "type": "uint256"
  71. }],
  72. "outputs": []
  73. }]
  74. `
  75. testContractInfo = `
  76. {
  77. "userDoc": ` + testUserDoc + `,
  78. "abiDefinition": ` + testAbiDefinition + `
  79. }
  80. `
  81. )
  82. type testFrontend struct {
  83. t *testing.T
  84. ethereum *eth.Ethereum
  85. xeth *xe.XEth
  86. wait chan *big.Int
  87. lastConfirm string
  88. wantNatSpec bool
  89. }
  90. func (self *testFrontend) UnlockAccount(acc []byte) bool {
  91. self.ethereum.AccountManager().Unlock(common.BytesToAddress(acc), "password")
  92. return true
  93. }
  94. func (self *testFrontend) ConfirmTransaction(tx string) bool {
  95. if self.wantNatSpec {
  96. ds := docserver.New("/tmp/")
  97. self.lastConfirm = GetNotice(self.xeth, tx, ds)
  98. }
  99. return true
  100. }
  101. func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {
  102. os.RemoveAll("/tmp/eth-natspec/")
  103. err = os.MkdirAll("/tmp/eth-natspec/keystore", os.ModePerm)
  104. if err != nil {
  105. panic(err)
  106. }
  107. // create a testAddress
  108. ks := crypto.NewKeyStorePassphrase("/tmp/eth-natspec/keystore")
  109. am := accounts.NewManager(ks)
  110. testAccount, err := am.NewAccount("password")
  111. if err != nil {
  112. panic(err)
  113. }
  114. testAddress := strings.TrimPrefix(testAccount.Address.Hex(), "0x")
  115. db, _ := ethdb.NewMemDatabase()
  116. // set up mock genesis with balance on the testAddress
  117. core.WriteGenesisBlockForTesting(db, common.HexToAddress(testAddress), common.String2Big(testBalance))
  118. // only use minimalistic stack with no networking
  119. ethereum, err = eth.New(&eth.Config{
  120. DataDir: "/tmp/eth-natspec",
  121. AccountManager: am,
  122. MaxPeers: 0,
  123. PowTest: true,
  124. Etherbase: common.HexToAddress(testAddress),
  125. NewDB: func(path string) (common.Database, error) { return db, nil },
  126. })
  127. if err != nil {
  128. panic(err)
  129. }
  130. return
  131. }
  132. func testInit(t *testing.T) (self *testFrontend) {
  133. // initialise and start minimal ethereum stack
  134. ethereum, err := testEth(t)
  135. if err != nil {
  136. t.Errorf("error creating ethereum: %v", err)
  137. return
  138. }
  139. err = ethereum.Start()
  140. if err != nil {
  141. t.Errorf("error starting ethereum: %v", err)
  142. return
  143. }
  144. // mock frontend
  145. self = &testFrontend{t: t, ethereum: ethereum}
  146. self.xeth = xe.New(ethereum, self)
  147. self.wait = self.xeth.UpdateState()
  148. addr, _ := self.ethereum.Etherbase()
  149. // initialise the registry contracts
  150. reg := registrar.New(self.xeth)
  151. var registrarTxhash, hashRegTxhash, urlHintTxhash string
  152. registrarTxhash, err = reg.SetGlobalRegistrar("", addr)
  153. if err != nil {
  154. t.Errorf("error creating GlobalRegistrar: %v", err)
  155. }
  156. hashRegTxhash, err = reg.SetHashReg("", addr)
  157. if err != nil {
  158. t.Errorf("error creating HashReg: %v", err)
  159. }
  160. urlHintTxhash, err = reg.SetUrlHint("", addr)
  161. if err != nil {
  162. t.Errorf("error creating UrlHint: %v", err)
  163. }
  164. if !processTxs(self, t, 3) {
  165. t.Errorf("error mining txs")
  166. }
  167. _ = registrarTxhash
  168. _ = hashRegTxhash
  169. _ = urlHintTxhash
  170. /* TODO:
  171. * lookup receipt and contract addresses by tx hash
  172. * name registration for HashReg and UrlHint addresses
  173. * mine those transactions
  174. * then set once more SetHashReg SetUrlHint
  175. */
  176. return
  177. }
  178. // end to end test
  179. func TestNatspecE2E(t *testing.T) {
  180. t.Skip()
  181. tf := testInit(t)
  182. defer tf.ethereum.Stop()
  183. addr, _ := tf.ethereum.Etherbase()
  184. // create a contractInfo file (mock cloud-deployed contract metadocs)
  185. // incidentally this is the info for the registry contract itself
  186. ioutil.WriteFile("/tmp/"+testFileName, []byte(testContractInfo), os.ModePerm)
  187. dochash := crypto.Sha3Hash([]byte(testContractInfo))
  188. // take the codehash for the contract we wanna test
  189. codeb := tf.xeth.CodeAtBytes(registrar.HashRegAddr)
  190. codehash := crypto.Sha3Hash(codeb)
  191. // use resolver to register codehash->dochash->url
  192. // test if globalregistry works
  193. // registrar.HashRefAddr = "0x0"
  194. // registrar.UrlHintAddr = "0x0"
  195. reg := registrar.New(tf.xeth)
  196. _, err := reg.SetHashToHash(addr, codehash, dochash)
  197. if err != nil {
  198. t.Errorf("error registering: %v", err)
  199. }
  200. _, err = reg.SetUrlToHash(addr, dochash, "file:///"+testFileName)
  201. if err != nil {
  202. t.Errorf("error registering: %v", err)
  203. }
  204. if !processTxs(tf, t, 5) {
  205. return
  206. }
  207. // NatSpec info for register method of HashReg contract installed
  208. // now using the same transactions to check confirm messages
  209. tf.wantNatSpec = true // this is set so now the backend uses natspec confirmation
  210. _, err = reg.SetHashToHash(addr, codehash, dochash)
  211. if err != nil {
  212. t.Errorf("error calling contract registry: %v", err)
  213. }
  214. fmt.Printf("GlobalRegistrar: %v, HashReg: %v, UrlHint: %v\n", registrar.GlobalRegistrarAddr, registrar.HashRegAddr, registrar.UrlHintAddr)
  215. if tf.lastConfirm != testExpNotice {
  216. t.Errorf("Wrong confirm message. expected\n'%v', got\n'%v'", testExpNotice, tf.lastConfirm)
  217. }
  218. // test unknown method
  219. exp := fmt.Sprintf(testExpNotice2, registrar.HashRegAddr)
  220. _, err = reg.SetOwner(addr)
  221. if err != nil {
  222. t.Errorf("error setting owner: %v", err)
  223. }
  224. if tf.lastConfirm != exp {
  225. t.Errorf("Wrong confirm message, expected\n'%v', got\n'%v'", exp, tf.lastConfirm)
  226. }
  227. // test unknown contract
  228. exp = fmt.Sprintf(testExpNotice3, registrar.UrlHintAddr)
  229. _, err = reg.SetUrlToHash(addr, dochash, "file:///test.content")
  230. if err != nil {
  231. t.Errorf("error registering: %v", err)
  232. }
  233. if tf.lastConfirm != exp {
  234. t.Errorf("Wrong confirm message, expected '%v', got '%v'", exp, tf.lastConfirm)
  235. }
  236. }
  237. func pendingTransactions(repl *testFrontend, t *testing.T) (txc int64, err error) {
  238. txs := repl.ethereum.TxPool().GetTransactions()
  239. return int64(len(txs)), nil
  240. }
  241. func processTxs(repl *testFrontend, t *testing.T, expTxc int) bool {
  242. var txc int64
  243. var err error
  244. for i := 0; i < 50; i++ {
  245. txc, err = pendingTransactions(repl, t)
  246. if err != nil {
  247. t.Errorf("unexpected error checking pending transactions: %v", err)
  248. return false
  249. }
  250. if expTxc < int(txc) {
  251. t.Errorf("too many pending transactions: expected %v, got %v", expTxc, txc)
  252. return false
  253. } else if expTxc == int(txc) {
  254. break
  255. }
  256. time.Sleep(100 * time.Millisecond)
  257. }
  258. if int(txc) != expTxc {
  259. t.Errorf("incorrect number of pending transactions, expected %v, got %v", expTxc, txc)
  260. return false
  261. }
  262. err = repl.ethereum.StartMining(runtime.NumCPU())
  263. if err != nil {
  264. t.Errorf("unexpected error mining: %v", err)
  265. return false
  266. }
  267. defer repl.ethereum.StopMining()
  268. timer := time.NewTimer(100 * time.Second)
  269. height := new(big.Int).Add(repl.xeth.CurrentBlock().Number(), big.NewInt(1))
  270. repl.wait <- height
  271. select {
  272. case <-timer.C:
  273. // if times out make sure the xeth loop does not block
  274. go func() {
  275. select {
  276. case repl.wait <- nil:
  277. case <-repl.wait:
  278. }
  279. }()
  280. case <-repl.wait:
  281. }
  282. txc, err = pendingTransactions(repl, t)
  283. if err != nil {
  284. t.Errorf("unexpected error checking pending transactions: %v", err)
  285. return false
  286. }
  287. if txc != 0 {
  288. t.Errorf("%d trasactions were not mined", txc)
  289. return false
  290. }
  291. return true
  292. }