xeth.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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.SetBeginBlock(earliest)
  474. filter.SetEndBlock(latest)
  475. filter.SetAddresses(cAddress(address))
  476. filter.SetTopics(cTopics(topics))
  477. filter.LogsCallback = func(logs vm.Logs) {
  478. self.logMu.Lock()
  479. defer self.logMu.Unlock()
  480. if queue := self.logQueue[id]; queue != nil {
  481. queue.add(logs...)
  482. }
  483. }
  484. return id
  485. }
  486. func (self *XEth) NewTransactionFilter() int {
  487. self.transactionMu.Lock()
  488. defer self.transactionMu.Unlock()
  489. filter := filters.New(self.backend.ChainDb())
  490. id := self.filterManager.Add(filter)
  491. self.transactionQueue[id] = &hashQueue{timeout: time.Now()}
  492. filter.TransactionCallback = func(tx *types.Transaction) {
  493. self.transactionMu.Lock()
  494. defer self.transactionMu.Unlock()
  495. if queue := self.transactionQueue[id]; queue != nil {
  496. queue.add(tx.Hash())
  497. }
  498. }
  499. return id
  500. }
  501. func (self *XEth) NewBlockFilter() int {
  502. self.blockMu.Lock()
  503. defer self.blockMu.Unlock()
  504. filter := filters.New(self.backend.ChainDb())
  505. id := self.filterManager.Add(filter)
  506. self.blockQueue[id] = &hashQueue{timeout: time.Now()}
  507. filter.BlockCallback = func(block *types.Block, logs vm.Logs) {
  508. self.blockMu.Lock()
  509. defer self.blockMu.Unlock()
  510. if queue := self.blockQueue[id]; queue != nil {
  511. queue.add(block.Hash())
  512. }
  513. }
  514. return id
  515. }
  516. func (self *XEth) GetFilterType(id int) byte {
  517. if _, ok := self.blockQueue[id]; ok {
  518. return BlockFilterTy
  519. } else if _, ok := self.transactionQueue[id]; ok {
  520. return TransactionFilterTy
  521. } else if _, ok := self.logQueue[id]; ok {
  522. return LogFilterTy
  523. }
  524. return UnknownFilterTy
  525. }
  526. func (self *XEth) LogFilterChanged(id int) vm.Logs {
  527. self.logMu.Lock()
  528. defer self.logMu.Unlock()
  529. if self.logQueue[id] != nil {
  530. return self.logQueue[id].get()
  531. }
  532. return nil
  533. }
  534. func (self *XEth) BlockFilterChanged(id int) []common.Hash {
  535. self.blockMu.Lock()
  536. defer self.blockMu.Unlock()
  537. if self.blockQueue[id] != nil {
  538. return self.blockQueue[id].get()
  539. }
  540. return nil
  541. }
  542. func (self *XEth) TransactionFilterChanged(id int) []common.Hash {
  543. self.blockMu.Lock()
  544. defer self.blockMu.Unlock()
  545. if self.transactionQueue[id] != nil {
  546. return self.transactionQueue[id].get()
  547. }
  548. return nil
  549. }
  550. func (self *XEth) Logs(id int) vm.Logs {
  551. filter := self.filterManager.Get(id)
  552. if filter != nil {
  553. return filter.Find()
  554. }
  555. return nil
  556. }
  557. func (self *XEth) AllLogs(earliest, latest int64, skip, max int, address []string, topics [][]string) vm.Logs {
  558. filter := filters.New(self.backend.ChainDb())
  559. filter.SetBeginBlock(earliest)
  560. filter.SetEndBlock(latest)
  561. filter.SetAddresses(cAddress(address))
  562. filter.SetTopics(cTopics(topics))
  563. return filter.Find()
  564. }
  565. // NewWhisperFilter creates and registers a new message filter to watch for
  566. // inbound whisper messages. All parameters at this point are assumed to be
  567. // HEX encoded.
  568. func (p *XEth) NewWhisperFilter(to, from string, topics [][]string) int {
  569. // Pre-define the id to be filled later
  570. var id int
  571. // Callback to delegate core whisper messages to this xeth filter
  572. callback := func(msg WhisperMessage) {
  573. p.messagesMu.RLock() // Only read lock to the filter pool
  574. defer p.messagesMu.RUnlock()
  575. p.messages[id].insert(msg)
  576. }
  577. // Initialize the core whisper filter and wrap into xeth
  578. id = p.Whisper().Watch(to, from, topics, callback)
  579. p.messagesMu.Lock()
  580. p.messages[id] = newWhisperFilter(id, p.Whisper())
  581. p.messagesMu.Unlock()
  582. return id
  583. }
  584. // UninstallWhisperFilter disables and removes an existing filter.
  585. func (p *XEth) UninstallWhisperFilter(id int) bool {
  586. p.messagesMu.Lock()
  587. defer p.messagesMu.Unlock()
  588. if _, ok := p.messages[id]; ok {
  589. delete(p.messages, id)
  590. return true
  591. }
  592. return false
  593. }
  594. // WhisperMessages retrieves all the known messages that match a specific filter.
  595. func (self *XEth) WhisperMessages(id int) []WhisperMessage {
  596. self.messagesMu.RLock()
  597. defer self.messagesMu.RUnlock()
  598. if self.messages[id] != nil {
  599. return self.messages[id].messages()
  600. }
  601. return nil
  602. }
  603. // WhisperMessagesChanged retrieves all the new messages matched by a filter
  604. // since the last retrieval
  605. func (self *XEth) WhisperMessagesChanged(id int) []WhisperMessage {
  606. self.messagesMu.RLock()
  607. defer self.messagesMu.RUnlock()
  608. if self.messages[id] != nil {
  609. return self.messages[id].retrieve()
  610. }
  611. return nil
  612. }
  613. // func (self *XEth) Register(args string) bool {
  614. // self.regmut.Lock()
  615. // defer self.regmut.Unlock()
  616. // if _, ok := self.register[args]; ok {
  617. // self.register[args] = nil // register with empty
  618. // }
  619. // return true
  620. // }
  621. // func (self *XEth) Unregister(args string) bool {
  622. // self.regmut.Lock()
  623. // defer self.regmut.Unlock()
  624. // if _, ok := self.register[args]; ok {
  625. // delete(self.register, args)
  626. // return true
  627. // }
  628. // return false
  629. // }
  630. // // TODO improve return type
  631. // func (self *XEth) PullWatchTx(args string) []*interface{} {
  632. // self.regmut.Lock()
  633. // defer self.regmut.Unlock()
  634. // txs := self.register[args]
  635. // self.register[args] = nil
  636. // return txs
  637. // }
  638. type KeyVal struct {
  639. Key string `json:"key"`
  640. Value string `json:"value"`
  641. }
  642. func (self *XEth) EachStorage(addr string) string {
  643. var values []KeyVal
  644. object := self.State().SafeGet(addr)
  645. it := object.Trie().Iterator()
  646. for it.Next() {
  647. values = append(values, KeyVal{common.ToHex(object.Trie().GetKey(it.Key)), common.ToHex(it.Value)})
  648. }
  649. valuesJson, err := json.Marshal(values)
  650. if err != nil {
  651. return ""
  652. }
  653. return string(valuesJson)
  654. }
  655. func (self *XEth) ToAscii(str string) string {
  656. padded := common.RightPadBytes([]byte(str), 32)
  657. return "0x" + common.ToHex(padded)
  658. }
  659. func (self *XEth) FromAscii(str string) string {
  660. if common.IsHex(str) {
  661. str = str[2:]
  662. }
  663. return string(bytes.Trim(common.FromHex(str), "\x00"))
  664. }
  665. func (self *XEth) FromNumber(str string) string {
  666. if common.IsHex(str) {
  667. str = str[2:]
  668. }
  669. return common.BigD(common.FromHex(str)).String()
  670. }
  671. func (self *XEth) PushTx(encodedTx string) (string, error) {
  672. tx := new(types.Transaction)
  673. err := rlp.DecodeBytes(common.FromHex(encodedTx), tx)
  674. if err != nil {
  675. glog.V(logger.Error).Infoln(err)
  676. return "", err
  677. }
  678. err = self.backend.TxPool().Add(tx)
  679. if err != nil {
  680. return "", err
  681. }
  682. if tx.To() == nil {
  683. from, err := tx.From()
  684. if err != nil {
  685. return "", err
  686. }
  687. addr := crypto.CreateAddress(from, tx.Nonce())
  688. glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr)
  689. } else {
  690. glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To())
  691. }
  692. return tx.Hash().Hex(), nil
  693. }
  694. func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) {
  695. statedb := self.State().State().Copy()
  696. var from *state.StateObject
  697. if len(fromStr) == 0 {
  698. accounts, err := self.backend.AccountManager().Accounts()
  699. if err != nil || len(accounts) == 0 {
  700. from = statedb.GetOrNewStateObject(common.Address{})
  701. } else {
  702. from = statedb.GetOrNewStateObject(accounts[0].Address)
  703. }
  704. } else {
  705. from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr))
  706. }
  707. from.SetBalance(common.MaxBig)
  708. from.SetGasLimit(common.MaxBig)
  709. msg := callmsg{
  710. from: from,
  711. gas: common.Big(gasStr),
  712. gasPrice: common.Big(gasPriceStr),
  713. value: common.Big(valueStr),
  714. data: common.FromHex(dataStr),
  715. }
  716. if len(toStr) > 0 {
  717. addr := common.HexToAddress(toStr)
  718. msg.to = &addr
  719. }
  720. if msg.gas.Cmp(big.NewInt(0)) == 0 {
  721. msg.gas = big.NewInt(50000000)
  722. }
  723. if msg.gasPrice.Cmp(big.NewInt(0)) == 0 {
  724. msg.gasPrice = self.DefaultGasPrice()
  725. }
  726. header := self.CurrentBlock().Header()
  727. vmenv := core.NewEnv(statedb, self.backend.BlockChain(), msg, header)
  728. res, gas, err := core.ApplyMessage(vmenv, msg, from)
  729. return common.ToHex(res), gas.String(), err
  730. }
  731. func (self *XEth) ConfirmTransaction(tx string) bool {
  732. return self.frontend.ConfirmTransaction(tx)
  733. }
  734. func (self *XEth) doSign(from common.Address, hash common.Hash, didUnlock bool) ([]byte, error) {
  735. sig, err := self.backend.AccountManager().Sign(accounts.Account{Address: from}, hash.Bytes())
  736. if err == accounts.ErrLocked {
  737. if didUnlock {
  738. return nil, fmt.Errorf("signer account still locked after successful unlock")
  739. }
  740. if !self.frontend.UnlockAccount(from.Bytes()) {
  741. return nil, fmt.Errorf("could not unlock signer account")
  742. }
  743. // retry signing, the account should now be unlocked.
  744. return self.doSign(from, hash, true)
  745. } else if err != nil {
  746. return nil, err
  747. }
  748. return sig, nil
  749. }
  750. func (self *XEth) Sign(fromStr, hashStr string, didUnlock bool) (string, error) {
  751. var (
  752. from = common.HexToAddress(fromStr)
  753. hash = common.HexToHash(hashStr)
  754. )
  755. sig, err := self.doSign(from, hash, didUnlock)
  756. if err != nil {
  757. return "", err
  758. }
  759. return common.ToHex(sig), nil
  760. }
  761. func isAddress(addr string) bool {
  762. return addrReg.MatchString(addr)
  763. }
  764. func (self *XEth) Frontend() Frontend {
  765. return self.frontend
  766. }
  767. func (self *XEth) Transact(fromStr, toStr, nonceStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {
  768. // this minimalistic recoding is enough (works for natspec.js)
  769. var jsontx = fmt.Sprintf(`{"params":[{"to":"%s","data": "%s"}]}`, toStr, codeStr)
  770. if !self.ConfirmTransaction(jsontx) {
  771. err := fmt.Errorf("Transaction not confirmed")
  772. return "", err
  773. }
  774. if len(toStr) > 0 && toStr != "0x" && !isAddress(toStr) {
  775. return "", errors.New("Invalid address")
  776. }
  777. var (
  778. from = common.HexToAddress(fromStr)
  779. to = common.HexToAddress(toStr)
  780. value = common.Big(valueStr)
  781. gas *big.Int
  782. price *big.Int
  783. data []byte
  784. contractCreation bool
  785. )
  786. if len(gasStr) == 0 {
  787. gas = DefaultGas()
  788. } else {
  789. gas = common.Big(gasStr)
  790. }
  791. if len(gasPriceStr) == 0 {
  792. price = self.DefaultGasPrice()
  793. } else {
  794. price = common.Big(gasPriceStr)
  795. }
  796. data = common.FromHex(codeStr)
  797. if len(toStr) == 0 {
  798. contractCreation = true
  799. }
  800. // 2015-05-18 Is this still needed?
  801. // TODO if no_private_key then
  802. //if _, exists := p.register[args.From]; exists {
  803. // p.register[args.From] = append(p.register[args.From], args)
  804. //} else {
  805. /*
  806. account := accounts.Get(common.FromHex(args.From))
  807. if account != nil {
  808. if account.Unlocked() {
  809. if !unlockAccount(account) {
  810. return
  811. }
  812. }
  813. result, _ := account.Transact(common.FromHex(args.To), common.FromHex(args.Value), common.FromHex(args.Gas), common.FromHex(args.GasPrice), common.FromHex(args.Data))
  814. if len(result) > 0 {
  815. *reply = common.ToHex(result)
  816. }
  817. } else if _, exists := p.register[args.From]; exists {
  818. p.register[ags.From] = append(p.register[args.From], args)
  819. }
  820. */
  821. self.transactMu.Lock()
  822. defer self.transactMu.Unlock()
  823. var nonce uint64
  824. if len(nonceStr) != 0 {
  825. nonce = common.Big(nonceStr).Uint64()
  826. } else {
  827. state := self.backend.TxPool().State()
  828. nonce = state.GetNonce(from)
  829. }
  830. var tx *types.Transaction
  831. if contractCreation {
  832. tx = types.NewContractCreation(nonce, value, gas, price, data)
  833. } else {
  834. tx = types.NewTransaction(nonce, to, value, gas, price, data)
  835. }
  836. signed, err := self.sign(tx, from, false)
  837. if err != nil {
  838. return "", err
  839. }
  840. if err = self.backend.TxPool().Add(signed); err != nil {
  841. return "", err
  842. }
  843. if contractCreation {
  844. addr := crypto.CreateAddress(from, nonce)
  845. glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signed.Hash().Hex(), addr.Hex())
  846. } else {
  847. glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signed.Hash().Hex(), tx.To().Hex())
  848. }
  849. return signed.Hash().Hex(), nil
  850. }
  851. func (self *XEth) sign(tx *types.Transaction, from common.Address, didUnlock bool) (*types.Transaction, error) {
  852. hash := tx.SigHash()
  853. sig, err := self.doSign(from, hash, didUnlock)
  854. if err != nil {
  855. return tx, err
  856. }
  857. return tx.WithSignature(sig)
  858. }
  859. // callmsg is the message type used for call transations.
  860. type callmsg struct {
  861. from *state.StateObject
  862. to *common.Address
  863. gas, gasPrice *big.Int
  864. value *big.Int
  865. data []byte
  866. }
  867. // accessor boilerplate to implement core.Message
  868. func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
  869. func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
  870. func (m callmsg) To() *common.Address { return m.to }
  871. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  872. func (m callmsg) Gas() *big.Int { return m.gas }
  873. func (m callmsg) Value() *big.Int { return m.value }
  874. func (m callmsg) Data() []byte { return m.data }
  875. type logQueue struct {
  876. mu sync.Mutex
  877. logs vm.Logs
  878. timeout time.Time
  879. id int
  880. }
  881. func (l *logQueue) add(logs ...*vm.Log) {
  882. l.mu.Lock()
  883. defer l.mu.Unlock()
  884. l.logs = append(l.logs, logs...)
  885. }
  886. func (l *logQueue) get() vm.Logs {
  887. l.mu.Lock()
  888. defer l.mu.Unlock()
  889. l.timeout = time.Now()
  890. tmp := l.logs
  891. l.logs = nil
  892. return tmp
  893. }
  894. type hashQueue struct {
  895. mu sync.Mutex
  896. hashes []common.Hash
  897. timeout time.Time
  898. id int
  899. }
  900. func (l *hashQueue) add(hashes ...common.Hash) {
  901. l.mu.Lock()
  902. defer l.mu.Unlock()
  903. l.hashes = append(l.hashes, hashes...)
  904. }
  905. func (l *hashQueue) get() []common.Hash {
  906. l.mu.Lock()
  907. defer l.mu.Unlock()
  908. l.timeout = time.Now()
  909. tmp := l.hashes
  910. l.hashes = nil
  911. return tmp
  912. }