xeth.go 27 KB

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