xeth.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. // Copyright 2014 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. // Package xeth is the interface to all Ethereum functionality.
  17. package xeth
  18. import (
  19. "bytes"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "regexp"
  25. "sync"
  26. "time"
  27. "github.com/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/compiler"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/eth"
  36. "github.com/ethereum/go-ethereum/eth/filters"
  37. "github.com/ethereum/go-ethereum/logger"
  38. "github.com/ethereum/go-ethereum/logger/glog"
  39. "github.com/ethereum/go-ethereum/miner"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. )
  42. var (
  43. filterTickerTime = 5 * time.Minute
  44. defaultGasPrice = big.NewInt(10000000000000) //150000000000
  45. defaultGas = big.NewInt(90000) //500000
  46. dappStorePre = []byte("dapp-")
  47. addrReg = regexp.MustCompile(`^(0x)?[a-fA-F0-9]{40}$`)
  48. )
  49. // byte will be inferred
  50. const (
  51. UnknownFilterTy = iota
  52. BlockFilterTy
  53. TransactionFilterTy
  54. LogFilterTy
  55. )
  56. func DefaultGas() *big.Int { return new(big.Int).Set(defaultGas) }
  57. func (self *XEth) DefaultGasPrice() *big.Int {
  58. if self.gpo == nil {
  59. self.gpo = eth.NewGasPriceOracle(self.backend)
  60. }
  61. return self.gpo.SuggestPrice()
  62. }
  63. type XEth struct {
  64. backend *eth.Ethereum
  65. frontend Frontend
  66. state *State
  67. whisper *Whisper
  68. quit chan struct{}
  69. filterManager *filters.FilterSystem
  70. logMu sync.RWMutex
  71. logQueue map[int]*logQueue
  72. blockMu sync.RWMutex
  73. blockQueue map[int]*hashQueue
  74. transactionMu sync.RWMutex
  75. transactionQueue map[int]*hashQueue
  76. messagesMu sync.RWMutex
  77. messages map[int]*whisperFilter
  78. transactMu sync.Mutex
  79. agent *miner.RemoteAgent
  80. gpo *eth.GasPriceOracle
  81. }
  82. func NewTest(eth *eth.Ethereum, frontend Frontend) *XEth {
  83. return &XEth{
  84. backend: eth,
  85. frontend: frontend,
  86. }
  87. }
  88. // New creates an XEth that uses the given frontend.
  89. // If a nil Frontend is provided, a default frontend which
  90. // confirms all transactions will be used.
  91. func New(ethereum *eth.Ethereum, frontend Frontend) *XEth {
  92. xeth := &XEth{
  93. backend: ethereum,
  94. frontend: frontend,
  95. quit: make(chan struct{}),
  96. filterManager: filters.NewFilterSystem(ethereum.EventMux()),
  97. logQueue: make(map[int]*logQueue),
  98. blockQueue: make(map[int]*hashQueue),
  99. transactionQueue: make(map[int]*hashQueue),
  100. messages: make(map[int]*whisperFilter),
  101. agent: miner.NewRemoteAgent(),
  102. }
  103. if ethereum.Whisper() != nil {
  104. xeth.whisper = NewWhisper(ethereum.Whisper())
  105. }
  106. ethereum.Miner().Register(xeth.agent)
  107. if frontend == nil {
  108. xeth.frontend = dummyFrontend{}
  109. }
  110. state, err := xeth.backend.BlockChain().State()
  111. if err != nil {
  112. return nil
  113. }
  114. xeth.state = NewState(xeth, state)
  115. go xeth.start()
  116. return xeth
  117. }
  118. func (self *XEth) start() {
  119. timer := time.NewTicker(2 * time.Second)
  120. done:
  121. for {
  122. select {
  123. case <-timer.C:
  124. self.logMu.Lock()
  125. for id, filter := range self.logQueue {
  126. if time.Since(filter.timeout) > filterTickerTime {
  127. self.filterManager.Remove(id)
  128. delete(self.logQueue, id)
  129. }
  130. }
  131. self.logMu.Unlock()
  132. self.blockMu.Lock()
  133. for id, filter := range self.blockQueue {
  134. if time.Since(filter.timeout) > filterTickerTime {
  135. self.filterManager.Remove(id)
  136. delete(self.blockQueue, id)
  137. }
  138. }
  139. self.blockMu.Unlock()
  140. self.transactionMu.Lock()
  141. for id, filter := range self.transactionQueue {
  142. if time.Since(filter.timeout) > filterTickerTime {
  143. self.filterManager.Remove(id)
  144. delete(self.transactionQueue, id)
  145. }
  146. }
  147. self.transactionMu.Unlock()
  148. self.messagesMu.Lock()
  149. for id, filter := range self.messages {
  150. if time.Since(filter.activity()) > filterTickerTime {
  151. self.Whisper().Unwatch(id)
  152. delete(self.messages, id)
  153. }
  154. }
  155. self.messagesMu.Unlock()
  156. case <-self.quit:
  157. break done
  158. }
  159. }
  160. }
  161. func (self *XEth) stop() {
  162. close(self.quit)
  163. }
  164. func cAddress(a []string) []common.Address {
  165. bslice := make([]common.Address, len(a))
  166. for i, addr := range a {
  167. bslice[i] = common.HexToAddress(addr)
  168. }
  169. return bslice
  170. }
  171. func cTopics(t [][]string) [][]common.Hash {
  172. topics := make([][]common.Hash, len(t))
  173. for i, iv := range t {
  174. topics[i] = make([]common.Hash, len(iv))
  175. for j, jv := range iv {
  176. topics[i][j] = common.HexToHash(jv)
  177. }
  178. }
  179. return topics
  180. }
  181. func (self *XEth) RemoteMining() *miner.RemoteAgent { return self.agent }
  182. func (self *XEth) AtStateNum(num int64) *XEth {
  183. var st *state.StateDB
  184. var err error
  185. switch num {
  186. case -2:
  187. st = self.backend.Miner().PendingState().Copy()
  188. default:
  189. if block := self.getBlockByHeight(num); block != nil {
  190. st, err = state.New(block.Root(), self.backend.ChainDb())
  191. if err != nil {
  192. return nil
  193. }
  194. } else {
  195. st, err = state.New(self.backend.BlockChain().GetBlockByNumber(0).Root(), self.backend.ChainDb())
  196. if err != nil {
  197. return nil
  198. }
  199. }
  200. }
  201. return self.WithState(st)
  202. }
  203. func (self *XEth) WithState(statedb *state.StateDB) *XEth {
  204. xeth := &XEth{
  205. backend: self.backend,
  206. frontend: self.frontend,
  207. gpo: self.gpo,
  208. }
  209. xeth.state = NewState(xeth, statedb)
  210. return xeth
  211. }
  212. func (self *XEth) State() *State { return self.state }
  213. // subscribes to new head block events and
  214. // waits until blockchain height is greater n at any time
  215. // given the current head, waits for the next chain event
  216. // sets the state to the current head
  217. // loop is async and quit by closing the channel
  218. // used in tests and JS console debug module to control advancing private chain manually
  219. // Note: this is not threadsafe, only called in JS single process and tests
  220. func (self *XEth) UpdateState() (wait chan *big.Int) {
  221. wait = make(chan *big.Int)
  222. go func() {
  223. eventSub := self.backend.EventMux().Subscribe(core.ChainHeadEvent{})
  224. defer eventSub.Unsubscribe()
  225. var m, n *big.Int
  226. var ok bool
  227. eventCh := eventSub.Chan()
  228. for {
  229. select {
  230. case event, ok := <-eventCh:
  231. if !ok {
  232. // Event subscription closed, set the channel to nil to stop spinning
  233. eventCh = nil
  234. continue
  235. }
  236. // A real event arrived, process if new head block assignment
  237. if event, ok := event.Data.(core.ChainHeadEvent); ok {
  238. m = event.Block.Number()
  239. if n != nil && n.Cmp(m) < 0 {
  240. wait <- n
  241. n = nil
  242. }
  243. statedb, err := state.New(event.Block.Root(), self.backend.ChainDb())
  244. if err != nil {
  245. glog.V(logger.Error).Infoln("Could not create new state: %v", err)
  246. return
  247. }
  248. self.state = NewState(self, statedb)
  249. }
  250. case n, ok = <-wait:
  251. if !ok {
  252. return
  253. }
  254. }
  255. }
  256. }()
  257. return
  258. }
  259. func (self *XEth) Whisper() *Whisper { return self.whisper }
  260. func (self *XEth) getBlockByHeight(height int64) *types.Block {
  261. var num uint64
  262. switch height {
  263. case -2:
  264. return self.backend.Miner().PendingBlock()
  265. case -1:
  266. return self.CurrentBlock()
  267. default:
  268. if height < 0 {
  269. return nil
  270. }
  271. num = uint64(height)
  272. }
  273. return self.backend.BlockChain().GetBlockByNumber(num)
  274. }
  275. func (self *XEth) BlockByHash(strHash string) *Block {
  276. hash := common.HexToHash(strHash)
  277. block := self.backend.BlockChain().GetBlock(hash)
  278. return NewBlock(block)
  279. }
  280. func (self *XEth) EthBlockByHash(strHash string) *types.Block {
  281. hash := common.HexToHash(strHash)
  282. block := self.backend.BlockChain().GetBlock(hash)
  283. return block
  284. }
  285. func (self *XEth) EthTransactionByHash(hash string) (tx *types.Transaction, blhash common.Hash, blnum *big.Int, txi uint64) {
  286. // Due to increasing return params and need to determine if this is from transaction pool or
  287. // some chain, this probably needs to be refactored for more expressiveness
  288. data, _ := self.backend.ChainDb().Get(common.FromHex(hash))
  289. if len(data) != 0 {
  290. dtx := new(types.Transaction)
  291. if err := rlp.DecodeBytes(data, dtx); err != nil {
  292. glog.V(logger.Error).Infoln(err)
  293. return
  294. }
  295. tx = dtx
  296. } else { // check pending transactions
  297. tx = self.backend.TxPool().GetTransaction(common.HexToHash(hash))
  298. }
  299. // meta
  300. var txExtra struct {
  301. BlockHash common.Hash
  302. BlockIndex uint64
  303. Index uint64
  304. }
  305. v, dberr := self.backend.ChainDb().Get(append(common.FromHex(hash), 0x0001))
  306. // TODO check specifically for ErrNotFound
  307. if dberr != nil {
  308. return
  309. }
  310. r := bytes.NewReader(v)
  311. err := rlp.Decode(r, &txExtra)
  312. if err == nil {
  313. blhash = txExtra.BlockHash
  314. blnum = big.NewInt(int64(txExtra.BlockIndex))
  315. txi = txExtra.Index
  316. } else {
  317. glog.V(logger.Error).Infoln(err)
  318. }
  319. return
  320. }
  321. func (self *XEth) BlockByNumber(num int64) *Block {
  322. return NewBlock(self.getBlockByHeight(num))
  323. }
  324. func (self *XEth) EthBlockByNumber(num int64) *types.Block {
  325. return self.getBlockByHeight(num)
  326. }
  327. func (self *XEth) Td(hash common.Hash) *big.Int {
  328. return self.backend.BlockChain().GetTd(hash)
  329. }
  330. func (self *XEth) CurrentBlock() *types.Block {
  331. return self.backend.BlockChain().CurrentBlock()
  332. }
  333. func (self *XEth) GetBlockReceipts(bhash common.Hash) types.Receipts {
  334. return self.backend.BlockProcessor().GetBlockReceipts(bhash)
  335. }
  336. func (self *XEth) GetTxReceipt(txhash common.Hash) *types.Receipt {
  337. return core.GetReceipt(self.backend.ChainDb(), txhash)
  338. }
  339. func (self *XEth) GasLimit() *big.Int {
  340. return self.backend.BlockChain().GasLimit()
  341. }
  342. func (self *XEth) Block(v interface{}) *Block {
  343. if n, ok := v.(int32); ok {
  344. return self.BlockByNumber(int64(n))
  345. } else if str, ok := v.(string); ok {
  346. return self.BlockByHash(str)
  347. } else if f, ok := v.(float64); ok { // JSON numbers are represented as float64
  348. return self.BlockByNumber(int64(f))
  349. }
  350. return nil
  351. }
  352. func (self *XEth) Accounts() []string {
  353. // TODO: check err?
  354. accounts, _ := self.backend.AccountManager().Accounts()
  355. accountAddresses := make([]string, len(accounts))
  356. for i, ac := range accounts {
  357. accountAddresses[i] = ac.Address.Hex()
  358. }
  359. return accountAddresses
  360. }
  361. // accessor for solidity compiler.
  362. // memoized if available, retried on-demand if not
  363. func (self *XEth) Solc() (*compiler.Solidity, error) {
  364. return self.backend.Solc()
  365. }
  366. // set in js console via admin interface or wrapper from cli flags
  367. func (self *XEth) SetSolc(solcPath string) (*compiler.Solidity, error) {
  368. self.backend.SetSolc(solcPath)
  369. return self.Solc()
  370. }
  371. // store DApp value in extra database
  372. func (self *XEth) DbPut(key, val []byte) bool {
  373. self.backend.DappDb().Put(append(dappStorePre, key...), val)
  374. return true
  375. }
  376. // retrieve DApp value from extra database
  377. func (self *XEth) DbGet(key []byte) ([]byte, error) {
  378. val, err := self.backend.DappDb().Get(append(dappStorePre, key...))
  379. return val, err
  380. }
  381. func (self *XEth) PeerCount() int {
  382. return self.backend.PeerCount()
  383. }
  384. func (self *XEth) IsMining() bool {
  385. return self.backend.IsMining()
  386. }
  387. func (self *XEth) HashRate() int64 {
  388. return self.backend.Miner().HashRate()
  389. }
  390. func (self *XEth) EthVersion() string {
  391. return fmt.Sprintf("%d", self.backend.EthVersion())
  392. }
  393. func (self *XEth) NetworkVersion() string {
  394. return fmt.Sprintf("%d", self.backend.NetVersion())
  395. }
  396. func (self *XEth) WhisperVersion() string {
  397. return fmt.Sprintf("%d", self.backend.ShhVersion())
  398. }
  399. func (self *XEth) ClientVersion() string {
  400. return self.backend.ClientVersion()
  401. }
  402. func (self *XEth) SetMining(shouldmine bool, threads int) bool {
  403. ismining := self.backend.IsMining()
  404. if shouldmine && !ismining {
  405. err := self.backend.StartMining(threads)
  406. return err == nil
  407. }
  408. if ismining && !shouldmine {
  409. self.backend.StopMining()
  410. }
  411. return self.backend.IsMining()
  412. }
  413. func (self *XEth) IsListening() bool {
  414. return self.backend.IsListening()
  415. }
  416. func (self *XEth) Coinbase() string {
  417. eb, err := self.backend.Etherbase()
  418. if err != nil {
  419. return "0x0"
  420. }
  421. return eb.Hex()
  422. }
  423. func (self *XEth) NumberToHuman(balance string) string {
  424. b := common.Big(balance)
  425. return common.CurrencyToString(b)
  426. }
  427. func (self *XEth) StorageAt(addr, storageAddr string) string {
  428. return self.State().state.GetState(common.HexToAddress(addr), common.HexToHash(storageAddr)).Hex()
  429. }
  430. func (self *XEth) BalanceAt(addr string) string {
  431. return common.ToHex(self.State().state.GetBalance(common.HexToAddress(addr)).Bytes())
  432. }
  433. func (self *XEth) TxCountAt(address string) int {
  434. return int(self.State().state.GetNonce(common.HexToAddress(address)))
  435. }
  436. func (self *XEth) CodeAt(address string) string {
  437. return common.ToHex(self.State().state.GetCode(common.HexToAddress(address)))
  438. }
  439. func (self *XEth) CodeAtBytes(address string) []byte {
  440. return self.State().SafeGet(address).Code()
  441. }
  442. func (self *XEth) IsContract(address string) bool {
  443. return len(self.State().SafeGet(address).Code()) > 0
  444. }
  445. func (self *XEth) UninstallFilter(id int) bool {
  446. defer self.filterManager.Remove(id)
  447. if _, ok := self.logQueue[id]; ok {
  448. self.logMu.Lock()
  449. defer self.logMu.Unlock()
  450. delete(self.logQueue, id)
  451. return true
  452. }
  453. if _, ok := self.blockQueue[id]; ok {
  454. self.blockMu.Lock()
  455. defer self.blockMu.Unlock()
  456. delete(self.blockQueue, id)
  457. return true
  458. }
  459. if _, ok := self.transactionQueue[id]; ok {
  460. self.transactionMu.Lock()
  461. defer self.transactionMu.Unlock()
  462. delete(self.transactionQueue, id)
  463. return true
  464. }
  465. return false
  466. }
  467. func (self *XEth) NewLogFilter(earliest, latest int64, skip, max int, address []string, topics [][]string) int {
  468. self.logMu.Lock()
  469. defer self.logMu.Unlock()
  470. filter := filters.New(self.backend.ChainDb())
  471. id := self.filterManager.Add(filter)
  472. self.logQueue[id] = &logQueue{timeout: time.Now()}
  473. filter.SetEarliestBlock(earliest)
  474. filter.SetLatestBlock(latest)
  475. filter.SetSkip(skip)
  476. filter.SetMax(max)
  477. filter.SetAddress(cAddress(address))
  478. filter.SetTopics(cTopics(topics))
  479. filter.LogsCallback = func(logs vm.Logs) {
  480. self.logMu.Lock()
  481. defer self.logMu.Unlock()
  482. if queue := self.logQueue[id]; queue != nil {
  483. queue.add(logs...)
  484. }
  485. }
  486. return id
  487. }
  488. func (self *XEth) NewTransactionFilter() int {
  489. self.transactionMu.Lock()
  490. defer self.transactionMu.Unlock()
  491. filter := filters.New(self.backend.ChainDb())
  492. id := self.filterManager.Add(filter)
  493. self.transactionQueue[id] = &hashQueue{timeout: time.Now()}
  494. filter.TransactionCallback = func(tx *types.Transaction) {
  495. self.transactionMu.Lock()
  496. defer self.transactionMu.Unlock()
  497. if queue := self.transactionQueue[id]; queue != nil {
  498. queue.add(tx.Hash())
  499. }
  500. }
  501. return id
  502. }
  503. func (self *XEth) NewBlockFilter() int {
  504. self.blockMu.Lock()
  505. defer self.blockMu.Unlock()
  506. filter := filters.New(self.backend.ChainDb())
  507. id := self.filterManager.Add(filter)
  508. self.blockQueue[id] = &hashQueue{timeout: time.Now()}
  509. filter.BlockCallback = func(block *types.Block, logs vm.Logs) {
  510. self.blockMu.Lock()
  511. defer self.blockMu.Unlock()
  512. if queue := self.blockQueue[id]; queue != nil {
  513. queue.add(block.Hash())
  514. }
  515. }
  516. return id
  517. }
  518. func (self *XEth) GetFilterType(id int) byte {
  519. if _, ok := self.blockQueue[id]; ok {
  520. return BlockFilterTy
  521. } else if _, ok := self.transactionQueue[id]; ok {
  522. return TransactionFilterTy
  523. } else if _, ok := self.logQueue[id]; ok {
  524. return LogFilterTy
  525. }
  526. return UnknownFilterTy
  527. }
  528. func (self *XEth) LogFilterChanged(id int) vm.Logs {
  529. self.logMu.Lock()
  530. defer self.logMu.Unlock()
  531. if self.logQueue[id] != nil {
  532. return self.logQueue[id].get()
  533. }
  534. return nil
  535. }
  536. func (self *XEth) BlockFilterChanged(id int) []common.Hash {
  537. self.blockMu.Lock()
  538. defer self.blockMu.Unlock()
  539. if self.blockQueue[id] != nil {
  540. return self.blockQueue[id].get()
  541. }
  542. return nil
  543. }
  544. func (self *XEth) TransactionFilterChanged(id int) []common.Hash {
  545. self.blockMu.Lock()
  546. defer self.blockMu.Unlock()
  547. if self.transactionQueue[id] != nil {
  548. return self.transactionQueue[id].get()
  549. }
  550. return nil
  551. }
  552. func (self *XEth) Logs(id int) vm.Logs {
  553. filter := self.filterManager.Get(id)
  554. if filter != nil {
  555. return filter.Find()
  556. }
  557. return nil
  558. }
  559. func (self *XEth) AllLogs(earliest, latest int64, skip, max int, address []string, topics [][]string) vm.Logs {
  560. filter := filters.New(self.backend.ChainDb())
  561. filter.SetEarliestBlock(earliest)
  562. filter.SetLatestBlock(latest)
  563. filter.SetSkip(skip)
  564. filter.SetMax(max)
  565. filter.SetAddress(cAddress(address))
  566. filter.SetTopics(cTopics(topics))
  567. return filter.Find()
  568. }
  569. // NewWhisperFilter creates and registers a new message filter to watch for
  570. // inbound whisper messages. All parameters at this point are assumed to be
  571. // HEX encoded.
  572. func (p *XEth) NewWhisperFilter(to, from string, topics [][]string) int {
  573. // Pre-define the id to be filled later
  574. var id int
  575. // Callback to delegate core whisper messages to this xeth filter
  576. callback := func(msg WhisperMessage) {
  577. p.messagesMu.RLock() // Only read lock to the filter pool
  578. defer p.messagesMu.RUnlock()
  579. p.messages[id].insert(msg)
  580. }
  581. // Initialize the core whisper filter and wrap into xeth
  582. id = p.Whisper().Watch(to, from, topics, callback)
  583. p.messagesMu.Lock()
  584. p.messages[id] = newWhisperFilter(id, p.Whisper())
  585. p.messagesMu.Unlock()
  586. return id
  587. }
  588. // UninstallWhisperFilter disables and removes an existing filter.
  589. func (p *XEth) UninstallWhisperFilter(id int) bool {
  590. p.messagesMu.Lock()
  591. defer p.messagesMu.Unlock()
  592. if _, ok := p.messages[id]; ok {
  593. delete(p.messages, id)
  594. return true
  595. }
  596. return false
  597. }
  598. // WhisperMessages retrieves all the known messages that match a specific filter.
  599. func (self *XEth) WhisperMessages(id int) []WhisperMessage {
  600. self.messagesMu.RLock()
  601. defer self.messagesMu.RUnlock()
  602. if self.messages[id] != nil {
  603. return self.messages[id].messages()
  604. }
  605. return nil
  606. }
  607. // WhisperMessagesChanged retrieves all the new messages matched by a filter
  608. // since the last retrieval
  609. func (self *XEth) WhisperMessagesChanged(id int) []WhisperMessage {
  610. self.messagesMu.RLock()
  611. defer self.messagesMu.RUnlock()
  612. if self.messages[id] != nil {
  613. return self.messages[id].retrieve()
  614. }
  615. return nil
  616. }
  617. // func (self *XEth) Register(args string) bool {
  618. // self.regmut.Lock()
  619. // defer self.regmut.Unlock()
  620. // if _, ok := self.register[args]; ok {
  621. // self.register[args] = nil // register with empty
  622. // }
  623. // return true
  624. // }
  625. // func (self *XEth) Unregister(args string) bool {
  626. // self.regmut.Lock()
  627. // defer self.regmut.Unlock()
  628. // if _, ok := self.register[args]; ok {
  629. // delete(self.register, args)
  630. // return true
  631. // }
  632. // return false
  633. // }
  634. // // TODO improve return type
  635. // func (self *XEth) PullWatchTx(args string) []*interface{} {
  636. // self.regmut.Lock()
  637. // defer self.regmut.Unlock()
  638. // txs := self.register[args]
  639. // self.register[args] = nil
  640. // return txs
  641. // }
  642. type KeyVal struct {
  643. Key string `json:"key"`
  644. Value string `json:"value"`
  645. }
  646. func (self *XEth) EachStorage(addr string) string {
  647. var values []KeyVal
  648. object := self.State().SafeGet(addr)
  649. it := object.Trie().Iterator()
  650. for it.Next() {
  651. values = append(values, KeyVal{common.ToHex(object.Trie().GetKey(it.Key)), common.ToHex(it.Value)})
  652. }
  653. valuesJson, err := json.Marshal(values)
  654. if err != nil {
  655. return ""
  656. }
  657. return string(valuesJson)
  658. }
  659. func (self *XEth) ToAscii(str string) string {
  660. padded := common.RightPadBytes([]byte(str), 32)
  661. return "0x" + common.ToHex(padded)
  662. }
  663. func (self *XEth) FromAscii(str string) string {
  664. if common.IsHex(str) {
  665. str = str[2:]
  666. }
  667. return string(bytes.Trim(common.FromHex(str), "\x00"))
  668. }
  669. func (self *XEth) FromNumber(str string) string {
  670. if common.IsHex(str) {
  671. str = str[2:]
  672. }
  673. return common.BigD(common.FromHex(str)).String()
  674. }
  675. func (self *XEth) PushTx(encodedTx string) (string, error) {
  676. tx := new(types.Transaction)
  677. err := rlp.DecodeBytes(common.FromHex(encodedTx), tx)
  678. if err != nil {
  679. glog.V(logger.Error).Infoln(err)
  680. return "", err
  681. }
  682. err = self.backend.TxPool().Add(tx)
  683. if err != nil {
  684. return "", err
  685. }
  686. if tx.To() == nil {
  687. from, err := tx.From()
  688. if err != nil {
  689. return "", err
  690. }
  691. addr := crypto.CreateAddress(from, tx.Nonce())
  692. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  693. } else {
  694. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  695. }
  696. return tx.Hash().Hex(), nil
  697. }
  698. func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) {
  699. statedb := self.State().State().Copy()
  700. var from *state.StateObject
  701. if len(fromStr) == 0 {
  702. accounts, err := self.backend.AccountManager().Accounts()
  703. if err != nil || len(accounts) == 0 {
  704. from = statedb.GetOrNewStateObject(common.Address{})
  705. } else {
  706. from = statedb.GetOrNewStateObject(accounts[0].Address)
  707. }
  708. } else {
  709. from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
  710. }
  711. from.SetBalance(common.MaxBig)
  712. from.SetGasLimit(common.MaxBig)
  713. msg := callmsg{
  714. from: from,
  715. gas: common.Big(gasStr),
  716. gasPrice: common.Big(gasPriceStr),
  717. value: common.Big(valueStr),
  718. data: common.FromHex(dataStr),
  719. }
  720. if len(toStr) > 0 {
  721. addr := common.HexToAddress(toStr)
  722. msg.to = &addr
  723. }
  724. if msg.gas.Cmp(big.NewInt(0)) == 0 {
  725. msg.gas = big.NewInt(50000000)
  726. }
  727. if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
  728. msg.gasPrice = self.DefaultGasPrice()
  729. }
  730. header := self.CurrentBlock().Header()
  731. vmenv := core.NewEnv(statedb, self.backend.BlockChain(), msg, header)
  732. res, gas, err := core.ApplyMessage(vmenv, msg, from)
  733. return common.ToHex(res), gas.String(), err
  734. }
  735. func (self *XEth) ConfirmTransaction(tx string) bool {
  736. return self.frontend.ConfirmTransaction(tx)
  737. }
  738. func (self *XEth) doSign(from common.Address, hash common.Hash, didUnlock bool) ([]byte, error) {
  739. sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from}, hash.Bytes())
  740. if err == accounts.ErrLocked {
  741. if didUnlock {
  742. return nil, fmt.Errorf("signer account still locked after successful unlock")
  743. }
  744. if !self.frontend.UnlockAccount(from.Bytes()) {
  745. return nil, fmt.Errorf("could not unlock signer account")
  746. }
  747. // retry signing, the account should now be unlocked.
  748. return self.doSign(from, hash, true)
  749. } else if err != nil {
  750. return nil, err
  751. }
  752. return sig, nil
  753. }
  754. func (self *XEth) Sign(fromStr, hashStr string, didUnlock bool) (string, error) {
  755. var (
  756. from = common.HexToAddress(fromStr)
  757. hash = common.HexToHash(hashStr)
  758. )
  759. sig, err := self.doSign(from, hash, didUnlock)
  760. if err != nil {
  761. return "", err
  762. }
  763. return common.ToHex(sig), nil
  764. }
  765. func isAddress(addr string) bool {
  766. return addrReg.MatchString(addr)
  767. }
  768. func (self *XEth) Frontend() Frontend {
  769. return self.frontend
  770. }
  771. func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {
  772. // this minimalistic recoding is enough (works for natspec.js)
  773. var jsontx = fmt.Sprintf(`{"params":[{"to":"%s","data": "%s"}]}`, toStr, codeStr)
  774. if !self.ConfirmTransaction(jsontx) {
  775. err := fmt.Errorf("Transaction not confirmed")
  776. return "", err
  777. }
  778. if len(toStr) > 0 && toStr != "0x" && !isAddress(toStr) {
  779. return "", errors.New("Invalid address")
  780. }
  781. var (
  782. from = common.HexToAddress(fromStr)
  783. to = common.HexToAddress(toStr)
  784. value = common.Big(valueStr)
  785. gas *big.Int
  786. price *big.Int
  787. data []byte
  788. contractCreation bool
  789. )
  790. if len(gasStr) == 0 {
  791. gas = DefaultGas()
  792. } else {
  793. gas = common.Big(gasStr)
  794. }
  795. if len(gasPriceStr) == 0 {
  796. price = self.DefaultGasPrice()
  797. } else {
  798. price = common.Big(gasPriceStr)
  799. }
  800. data = common.FromHex(codeStr)
  801. if len(toStr) == 0 {
  802. contractCreation = true
  803. }
  804. // 2015-05-18 Is this still needed?
  805. // TODO if no_private_key then
  806. //if _, exists := p.register[args.From]; exists {
  807. // p.register[args.From] = append(p.register[args.From], args)
  808. //} else {
  809. /*
  810. account := accounts.Get(common.FromHex(args.From))
  811. if account != nil {
  812. if account.Unlocked() {
  813. if !unlockAccount(account) {
  814. return
  815. }
  816. }
  817. result, _ := account.Transact(common.FromHex(args.To), common.FromHex(args.Value), common.FromHex(args.Gas), common.FromHex(args.GasPrice), common.FromHex(args.Data))
  818. if len(result) > 0 {
  819. *reply = common.ToHex(result)
  820. }
  821. } else if _, exists := p.register[args.From]; exists {
  822. p.register[ags.From] = append(p.register[args.From], args)
  823. }
  824. */
  825. self.transactMu.Lock()
  826. defer self.transactMu.Unlock()
  827. var nonce uint64
  828. if len(nonceStr) != 0 {
  829. nonce = common.Big(nonceStr).Uint64()
  830. } else {
  831. state := self.backend.TxPool().State()
  832. nonce = state.GetNonce(from)
  833. }
  834. var tx *types.Transaction
  835. if contractCreation {
  836. tx = types.NewContractCreation(nonce, value, gas, price, data)
  837. } else {
  838. tx = types.NewTransaction(nonce, to, value, gas, price, data)
  839. }
  840. signed, err := self.sign(tx, from, false)
  841. if err != nil {
  842. return "", err
  843. }
  844. if err = self.backend.TxPool().Add(signed); err != nil {
  845. return "", err
  846. }
  847. if contractCreation {
  848. addr := crypto.CreateAddress(from, nonce)
  849. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signed.Hash().Hex(), addr.Hex())
  850. } else {
  851. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signed.Hash().Hex(), tx.To().Hex())
  852. }
  853. return signed.Hash().Hex(), nil
  854. }
  855. func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) (*types.Transaction, error) {
  856. hash := tx.SigHash()
  857. sig, err := self.doSign(from, hash, didUnlock)
  858. if err != nil {
  859. return tx, err
  860. }
  861. return tx.WithSignature(sig)
  862. }
  863. // callmsg is the message type used for call transations.
  864. type callmsg struct {
  865. from *state.StateObject
  866. to *common.Address
  867. gas, gasPrice *big.Int
  868. value *big.Int
  869. data []byte
  870. }
  871. // accessor boilerplate to implement core.Message
  872. func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
  873. func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
  874. func (m callmsg) To() *common.Address { return m.to }
  875. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  876. func (m callmsg) Gas() *big.Int { return m.gas }
  877. func (m callmsg) Value() *big.Int { return m.value }
  878. func (m callmsg) Data() []byte { return m.data }
  879. type logQueue struct {
  880. mu sync.Mutex
  881. logs vm.Logs
  882. timeout time.Time
  883. id int
  884. }
  885. func (l *logQueue) add(logs ...*vm.Log) {
  886. l.mu.Lock()
  887. defer l.mu.Unlock()
  888. l.logs = append(l.logs, logs...)
  889. }
  890. func (l *logQueue) get() vm.Logs {
  891. l.mu.Lock()
  892. defer l.mu.Unlock()
  893. l.timeout = time.Now()
  894. tmp := l.logs
  895. l.logs = nil
  896. return tmp
  897. }
  898. type hashQueue struct {
  899. mu sync.Mutex
  900. hashes []common.Hash
  901. timeout time.Time
  902. id int
  903. }
  904. func (l *hashQueue) add(hashes ...common.Hash) {
  905. l.mu.Lock()
  906. defer l.mu.Unlock()
  907. l.hashes = append(l.hashes, hashes...)
  908. }
  909. func (l *hashQueue) get() []common.Hash {
  910. l.mu.Lock()
  911. defer l.mu.Unlock()
  912. l.timeout = time.Now()
  913. tmp := l.hashes
  914. l.hashes = nil
  915. return tmp
  916. }