natspec_e2e_test.go 9.9 KB

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