xeth.go 25 KB

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