api.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package ethapi
  17. import (
  18. "bytes"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "strings"
  24. "time"
  25. "github.com/davecgh/go-spew/spew"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/accounts/keystore"
  28. "github.com/ethereum/go-ethereum/accounts/scwallet"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/hexutil"
  31. "github.com/ethereum/go-ethereum/common/math"
  32. "github.com/ethereum/go-ethereum/consensus/clique"
  33. "github.com/ethereum/go-ethereum/consensus/ethash"
  34. "github.com/ethereum/go-ethereum/core"
  35. "github.com/ethereum/go-ethereum/core/rawdb"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/core/vm"
  38. "github.com/ethereum/go-ethereum/crypto"
  39. "github.com/ethereum/go-ethereum/log"
  40. "github.com/ethereum/go-ethereum/p2p"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/rlp"
  43. "github.com/ethereum/go-ethereum/rpc"
  44. "github.com/tyler-smith/go-bip39"
  45. )
  46. // PublicEthereumAPI provides an API to access Ethereum related information.
  47. // It offers only methods that operate on public data that is freely available to anyone.
  48. type PublicEthereumAPI struct {
  49. b Backend
  50. }
  51. // NewPublicEthereumAPI creates a new Ethereum protocol API.
  52. func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
  53. return &PublicEthereumAPI{b}
  54. }
  55. // GasPrice returns a suggestion for a gas price.
  56. func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
  57. price, err := s.b.SuggestPrice(ctx)
  58. return (*hexutil.Big)(price), err
  59. }
  60. // ProtocolVersion returns the current Ethereum protocol version this node supports
  61. func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {
  62. return hexutil.Uint(s.b.ProtocolVersion())
  63. }
  64. // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  65. // yet received the latest block headers from its pears. In case it is synchronizing:
  66. // - startingBlock: block number this node started to synchronise from
  67. // - currentBlock: block number this node is currently importing
  68. // - highestBlock: block number of the highest block header this node has received from peers
  69. // - pulledStates: number of state entries processed until now
  70. // - knownStates: number of known state entries that still need to be pulled
  71. func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
  72. progress := s.b.Downloader().Progress()
  73. // Return not syncing if the synchronisation already completed
  74. if progress.CurrentBlock >= progress.HighestBlock {
  75. return false, nil
  76. }
  77. // Otherwise gather the block sync stats
  78. return map[string]interface{}{
  79. "startingBlock": hexutil.Uint64(progress.StartingBlock),
  80. "currentBlock": hexutil.Uint64(progress.CurrentBlock),
  81. "highestBlock": hexutil.Uint64(progress.HighestBlock),
  82. "pulledStates": hexutil.Uint64(progress.PulledStates),
  83. "knownStates": hexutil.Uint64(progress.KnownStates),
  84. }, nil
  85. }
  86. // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
  87. type PublicTxPoolAPI struct {
  88. b Backend
  89. }
  90. // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
  91. func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
  92. return &PublicTxPoolAPI{b}
  93. }
  94. // Content returns the transactions contained within the transaction pool.
  95. func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
  96. content := map[string]map[string]map[string]*RPCTransaction{
  97. "pending": make(map[string]map[string]*RPCTransaction),
  98. "queued": make(map[string]map[string]*RPCTransaction),
  99. }
  100. pending, queue := s.b.TxPoolContent()
  101. // Flatten the pending transactions
  102. for account, txs := range pending {
  103. dump := make(map[string]*RPCTransaction)
  104. for _, tx := range txs {
  105. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
  106. }
  107. content["pending"][account.Hex()] = dump
  108. }
  109. // Flatten the queued transactions
  110. for account, txs := range queue {
  111. dump := make(map[string]*RPCTransaction)
  112. for _, tx := range txs {
  113. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
  114. }
  115. content["queued"][account.Hex()] = dump
  116. }
  117. return content
  118. }
  119. // Status returns the number of pending and queued transaction in the pool.
  120. func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
  121. pending, queue := s.b.Stats()
  122. return map[string]hexutil.Uint{
  123. "pending": hexutil.Uint(pending),
  124. "queued": hexutil.Uint(queue),
  125. }
  126. }
  127. // Inspect retrieves the content of the transaction pool and flattens it into an
  128. // easily inspectable list.
  129. func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
  130. content := map[string]map[string]map[string]string{
  131. "pending": make(map[string]map[string]string),
  132. "queued": make(map[string]map[string]string),
  133. }
  134. pending, queue := s.b.TxPoolContent()
  135. // Define a formatter to flatten a transaction into a string
  136. var format = func(tx *types.Transaction) string {
  137. if to := tx.To(); to != nil {
  138. return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
  139. }
  140. return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
  141. }
  142. // Flatten the pending transactions
  143. for account, txs := range pending {
  144. dump := make(map[string]string)
  145. for _, tx := range txs {
  146. dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
  147. }
  148. content["pending"][account.Hex()] = dump
  149. }
  150. // Flatten the queued transactions
  151. for account, txs := range queue {
  152. dump := make(map[string]string)
  153. for _, tx := range txs {
  154. dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
  155. }
  156. content["queued"][account.Hex()] = dump
  157. }
  158. return content
  159. }
  160. // PublicAccountAPI provides an API to access accounts managed by this node.
  161. // It offers only methods that can retrieve accounts.
  162. type PublicAccountAPI struct {
  163. am *accounts.Manager
  164. }
  165. // NewPublicAccountAPI creates a new PublicAccountAPI.
  166. func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
  167. return &PublicAccountAPI{am: am}
  168. }
  169. // Accounts returns the collection of accounts this node manages
  170. func (s *PublicAccountAPI) Accounts() []common.Address {
  171. return s.am.Accounts()
  172. }
  173. // PrivateAccountAPI provides an API to access accounts managed by this node.
  174. // It offers methods to create, (un)lock en list accounts. Some methods accept
  175. // passwords and are therefore considered private by default.
  176. type PrivateAccountAPI struct {
  177. am *accounts.Manager
  178. nonceLock *AddrLocker
  179. b Backend
  180. }
  181. // NewPrivateAccountAPI create a new PrivateAccountAPI.
  182. func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
  183. return &PrivateAccountAPI{
  184. am: b.AccountManager(),
  185. nonceLock: nonceLock,
  186. b: b,
  187. }
  188. }
  189. // listAccounts will return a list of addresses for accounts this node manages.
  190. func (s *PrivateAccountAPI) ListAccounts() []common.Address {
  191. return s.am.Accounts()
  192. }
  193. // rawWallet is a JSON representation of an accounts.Wallet interface, with its
  194. // data contents extracted into plain fields.
  195. type rawWallet struct {
  196. URL string `json:"url"`
  197. Status string `json:"status"`
  198. Failure string `json:"failure,omitempty"`
  199. Accounts []accounts.Account `json:"accounts,omitempty"`
  200. }
  201. // ListWallets will return a list of wallets this node manages.
  202. func (s *PrivateAccountAPI) ListWallets() []rawWallet {
  203. wallets := make([]rawWallet, 0) // return [] instead of nil if empty
  204. for _, wallet := range s.am.Wallets() {
  205. status, failure := wallet.Status()
  206. raw := rawWallet{
  207. URL: wallet.URL().String(),
  208. Status: status,
  209. Accounts: wallet.Accounts(),
  210. }
  211. if failure != nil {
  212. raw.Failure = failure.Error()
  213. }
  214. wallets = append(wallets, raw)
  215. }
  216. return wallets
  217. }
  218. // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
  219. // connection and attempting to authenticate via the provided passphrase. Note,
  220. // the method may return an extra challenge requiring a second open (e.g. the
  221. // Trezor PIN matrix challenge).
  222. func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
  223. wallet, err := s.am.Wallet(url)
  224. if err != nil {
  225. return err
  226. }
  227. pass := ""
  228. if passphrase != nil {
  229. pass = *passphrase
  230. }
  231. return wallet.Open(pass)
  232. }
  233. // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
  234. // it for later reuse.
  235. func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
  236. wallet, err := s.am.Wallet(url)
  237. if err != nil {
  238. return accounts.Account{}, err
  239. }
  240. derivPath, err := accounts.ParseDerivationPath(path)
  241. if err != nil {
  242. return accounts.Account{}, err
  243. }
  244. if pin == nil {
  245. pin = new(bool)
  246. }
  247. return wallet.Derive(derivPath, *pin)
  248. }
  249. // NewAccount will create a new account and returns the address for the new account.
  250. func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
  251. acc, err := fetchKeystore(s.am).NewAccount(password)
  252. if err == nil {
  253. log.Info("Your new key was generated", "address", acc.Address)
  254. log.Warn("Please backup your key file!", "path", acc.URL.Path)
  255. log.Warn("Please remember your password!")
  256. return acc.Address, nil
  257. }
  258. return common.Address{}, err
  259. }
  260. // fetchKeystore retrives the encrypted keystore from the account manager.
  261. func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
  262. return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  263. }
  264. // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
  265. // encrypting it with the passphrase.
  266. func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
  267. key, err := crypto.HexToECDSA(privkey)
  268. if err != nil {
  269. return common.Address{}, err
  270. }
  271. acc, err := fetchKeystore(s.am).ImportECDSA(key, password)
  272. return acc.Address, err
  273. }
  274. // UnlockAccount will unlock the account associated with the given address with
  275. // the given password for duration seconds. If duration is nil it will use a
  276. // default of 300 seconds. It returns an indication if the account was unlocked.
  277. func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
  278. // When the API is exposed by external RPC(http, ws etc), unless the user
  279. // explicitly specifies to allow the insecure account unlocking, otherwise
  280. // it is disabled.
  281. if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed {
  282. return false, errors.New("account unlock with HTTP access is forbidden")
  283. }
  284. const max = uint64(time.Duration(math.MaxInt64) / time.Second)
  285. var d time.Duration
  286. if duration == nil {
  287. d = 300 * time.Second
  288. } else if *duration > max {
  289. return false, errors.New("unlock duration too large")
  290. } else {
  291. d = time.Duration(*duration) * time.Second
  292. }
  293. err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d)
  294. if err != nil {
  295. log.Warn("Failed account unlock attempt", "address", addr, "err", err)
  296. }
  297. return err == nil, err
  298. }
  299. // LockAccount will lock the account associated with the given address when it's unlocked.
  300. func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
  301. return fetchKeystore(s.am).Lock(addr) == nil
  302. }
  303. // signTransaction sets defaults and signs the given transaction
  304. // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
  305. // and release it after the transaction has been submitted to the tx pool
  306. func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) {
  307. // Look up the wallet containing the requested signer
  308. account := accounts.Account{Address: args.From}
  309. wallet, err := s.am.Find(account)
  310. if err != nil {
  311. return nil, err
  312. }
  313. // Set some sanity defaults and terminate on failure
  314. if err := args.setDefaults(ctx, s.b); err != nil {
  315. return nil, err
  316. }
  317. // Assemble the transaction and sign with the wallet
  318. tx := args.toTransaction()
  319. return wallet.SignTxWithPassphrase(account, passwd, tx, s.b.ChainConfig().ChainID)
  320. }
  321. // SendTransaction will create a transaction from the given arguments and
  322. // tries to sign it with the key associated with args.To. If the given passwd isn't
  323. // able to decrypt the key it fails.
  324. func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  325. if args.Nonce == nil {
  326. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  327. // the same nonce to multiple accounts.
  328. s.nonceLock.LockAddr(args.From)
  329. defer s.nonceLock.UnlockAddr(args.From)
  330. }
  331. signed, err := s.signTransaction(ctx, &args, passwd)
  332. if err != nil {
  333. log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  334. return common.Hash{}, err
  335. }
  336. return SubmitTransaction(ctx, s.b, signed)
  337. }
  338. // SignTransaction will create a transaction from the given arguments and
  339. // tries to sign it with the key associated with args.To. If the given passwd isn't
  340. // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
  341. // to other nodes
  342. func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
  343. // No need to obtain the noncelock mutex, since we won't be sending this
  344. // tx into the transaction pool, but right back to the user
  345. if args.Gas == nil {
  346. return nil, fmt.Errorf("gas not specified")
  347. }
  348. if args.GasPrice == nil {
  349. return nil, fmt.Errorf("gasPrice not specified")
  350. }
  351. if args.Nonce == nil {
  352. return nil, fmt.Errorf("nonce not specified")
  353. }
  354. signed, err := s.signTransaction(ctx, &args, passwd)
  355. if err != nil {
  356. log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  357. return nil, err
  358. }
  359. data, err := rlp.EncodeToBytes(signed)
  360. if err != nil {
  361. return nil, err
  362. }
  363. return &SignTransactionResult{data, signed}, nil
  364. }
  365. // Sign calculates an Ethereum ECDSA signature for:
  366. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  367. //
  368. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  369. // where the V value will be 27 or 28 for legacy reasons.
  370. //
  371. // The key used to calculate the signature is decrypted with the given password.
  372. //
  373. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  374. func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
  375. // Look up the wallet containing the requested signer
  376. account := accounts.Account{Address: addr}
  377. wallet, err := s.b.AccountManager().Find(account)
  378. if err != nil {
  379. return nil, err
  380. }
  381. // Assemble sign the data with the wallet
  382. signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
  383. if err != nil {
  384. log.Warn("Failed data sign attempt", "address", addr, "err", err)
  385. return nil, err
  386. }
  387. signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  388. return signature, nil
  389. }
  390. // EcRecover returns the address for the account that was used to create the signature.
  391. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  392. // the address of:
  393. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  394. // addr = ecrecover(hash, signature)
  395. //
  396. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  397. // the V value must be 27 or 28 for legacy reasons.
  398. //
  399. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  400. func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  401. if len(sig) != crypto.SignatureLength {
  402. return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
  403. }
  404. if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
  405. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  406. }
  407. sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
  408. rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
  409. if err != nil {
  410. return common.Address{}, err
  411. }
  412. return crypto.PubkeyToAddress(*rpk), nil
  413. }
  414. // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
  415. // and will be removed in the future. It primary goal is to give clients time to update.
  416. func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  417. return s.SendTransaction(ctx, args, passwd)
  418. }
  419. // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
  420. func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
  421. wallet, err := s.am.Wallet(url)
  422. if err != nil {
  423. return "", err
  424. }
  425. entropy, err := bip39.NewEntropy(256)
  426. if err != nil {
  427. return "", err
  428. }
  429. mnemonic, err := bip39.NewMnemonic(entropy)
  430. if err != nil {
  431. return "", err
  432. }
  433. seed := bip39.NewSeed(mnemonic, "")
  434. switch wallet := wallet.(type) {
  435. case *scwallet.Wallet:
  436. return mnemonic, wallet.Initialize(seed)
  437. default:
  438. return "", fmt.Errorf("specified wallet does not support initialization")
  439. }
  440. }
  441. // Unpair deletes a pairing between wallet and geth.
  442. func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
  443. wallet, err := s.am.Wallet(url)
  444. if err != nil {
  445. return err
  446. }
  447. switch wallet := wallet.(type) {
  448. case *scwallet.Wallet:
  449. return wallet.Unpair([]byte(pin))
  450. default:
  451. return fmt.Errorf("specified wallet does not support pairing")
  452. }
  453. }
  454. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  455. // It offers only methods that operate on public data that is freely available to anyone.
  456. type PublicBlockChainAPI struct {
  457. b Backend
  458. }
  459. // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
  460. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  461. return &PublicBlockChainAPI{b}
  462. }
  463. // ChainId returns the chainID value for transaction replay protection.
  464. func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
  465. return (*hexutil.Big)(s.b.ChainConfig().ChainID)
  466. }
  467. // BlockNumber returns the block number of the chain head.
  468. func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
  469. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  470. return hexutil.Uint64(header.Number.Uint64())
  471. }
  472. // GetBalance returns the amount of wei for the given address in the state of the
  473. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  474. // block numbers are also allowed.
  475. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
  476. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  477. if state == nil || err != nil {
  478. return nil, err
  479. }
  480. return (*hexutil.Big)(state.GetBalance(address)), state.Error()
  481. }
  482. // Result structs for GetProof
  483. type AccountResult struct {
  484. Address common.Address `json:"address"`
  485. AccountProof []string `json:"accountProof"`
  486. Balance *hexutil.Big `json:"balance"`
  487. CodeHash common.Hash `json:"codeHash"`
  488. Nonce hexutil.Uint64 `json:"nonce"`
  489. StorageHash common.Hash `json:"storageHash"`
  490. StorageProof []StorageResult `json:"storageProof"`
  491. }
  492. type StorageResult struct {
  493. Key string `json:"key"`
  494. Value *hexutil.Big `json:"value"`
  495. Proof []string `json:"proof"`
  496. }
  497. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
  498. func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
  499. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  500. if state == nil || err != nil {
  501. return nil, err
  502. }
  503. storageTrie := state.StorageTrie(address)
  504. storageHash := types.EmptyRootHash
  505. codeHash := state.GetCodeHash(address)
  506. storageProof := make([]StorageResult, len(storageKeys))
  507. // if we have a storageTrie, (which means the account exists), we can update the storagehash
  508. if storageTrie != nil {
  509. storageHash = storageTrie.Hash()
  510. } else {
  511. // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
  512. codeHash = crypto.Keccak256Hash(nil)
  513. }
  514. // create the proof for the storageKeys
  515. for i, key := range storageKeys {
  516. if storageTrie != nil {
  517. proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
  518. if storageError != nil {
  519. return nil, storageError
  520. }
  521. storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
  522. } else {
  523. storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
  524. }
  525. }
  526. // create the accountProof
  527. accountProof, proofErr := state.GetProof(address)
  528. if proofErr != nil {
  529. return nil, proofErr
  530. }
  531. return &AccountResult{
  532. Address: address,
  533. AccountProof: common.ToHexArray(accountProof),
  534. Balance: (*hexutil.Big)(state.GetBalance(address)),
  535. CodeHash: codeHash,
  536. Nonce: hexutil.Uint64(state.GetNonce(address)),
  537. StorageHash: storageHash,
  538. StorageProof: storageProof,
  539. }, state.Error()
  540. }
  541. // GetHeaderByNumber returns the requested canonical block header.
  542. // * When blockNr is -1 the chain head is returned.
  543. // * When blockNr is -2 the pending chain head is returned.
  544. func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
  545. header, err := s.b.HeaderByNumber(ctx, number)
  546. if header != nil && err == nil {
  547. response := s.rpcMarshalHeader(header)
  548. if number == rpc.PendingBlockNumber {
  549. // Pending header need to nil out a few fields
  550. for _, field := range []string{"hash", "nonce", "miner"} {
  551. response[field] = nil
  552. }
  553. }
  554. return response, err
  555. }
  556. return nil, err
  557. }
  558. // GetHeaderByHash returns the requested header by hash.
  559. func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
  560. header, _ := s.b.HeaderByHash(ctx, hash)
  561. if header != nil {
  562. return s.rpcMarshalHeader(header)
  563. }
  564. return nil
  565. }
  566. // GetBlockByNumber returns the requested canonical block.
  567. // * When blockNr is -1 the chain head is returned.
  568. // * When blockNr is -2 the pending chain head is returned.
  569. // * When fullTx is true all transactions in the block are returned, otherwise
  570. // only the transaction hash is returned.
  571. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  572. block, err := s.b.BlockByNumber(ctx, number)
  573. if block != nil && err == nil {
  574. response, err := s.rpcMarshalBlock(block, true, fullTx)
  575. if err == nil && number == rpc.PendingBlockNumber {
  576. // Pending blocks need to nil out a few fields
  577. for _, field := range []string{"hash", "nonce", "miner"} {
  578. response[field] = nil
  579. }
  580. }
  581. return response, err
  582. }
  583. return nil, err
  584. }
  585. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  586. // detail, otherwise only the transaction hash is returned.
  587. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
  588. block, err := s.b.BlockByHash(ctx, hash)
  589. if block != nil {
  590. return s.rpcMarshalBlock(block, true, fullTx)
  591. }
  592. return nil, err
  593. }
  594. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  595. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  596. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  597. block, err := s.b.BlockByNumber(ctx, blockNr)
  598. if block != nil {
  599. uncles := block.Uncles()
  600. if index >= hexutil.Uint(len(uncles)) {
  601. log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
  602. return nil, nil
  603. }
  604. block = types.NewBlockWithHeader(uncles[index])
  605. return s.rpcMarshalBlock(block, false, false)
  606. }
  607. return nil, err
  608. }
  609. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  610. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  611. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  612. block, err := s.b.BlockByHash(ctx, blockHash)
  613. if block != nil {
  614. uncles := block.Uncles()
  615. if index >= hexutil.Uint(len(uncles)) {
  616. log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
  617. return nil, nil
  618. }
  619. block = types.NewBlockWithHeader(uncles[index])
  620. return s.rpcMarshalBlock(block, false, false)
  621. }
  622. return nil, err
  623. }
  624. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  625. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  626. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  627. n := hexutil.Uint(len(block.Uncles()))
  628. return &n
  629. }
  630. return nil
  631. }
  632. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  633. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  634. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  635. n := hexutil.Uint(len(block.Uncles()))
  636. return &n
  637. }
  638. return nil
  639. }
  640. // GetCode returns the code stored at the given address in the state for the given block number.
  641. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  642. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  643. if state == nil || err != nil {
  644. return nil, err
  645. }
  646. code := state.GetCode(address)
  647. return code, state.Error()
  648. }
  649. // GetStorageAt returns the storage from the state at the given address, key and
  650. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  651. // numbers are also allowed.
  652. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  653. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  654. if state == nil || err != nil {
  655. return nil, err
  656. }
  657. res := state.GetState(address, common.HexToHash(key))
  658. return res[:], state.Error()
  659. }
  660. // CallArgs represents the arguments for a call.
  661. type CallArgs struct {
  662. From *common.Address `json:"from"`
  663. To *common.Address `json:"to"`
  664. Gas *hexutil.Uint64 `json:"gas"`
  665. GasPrice *hexutil.Big `json:"gasPrice"`
  666. Value *hexutil.Big `json:"value"`
  667. Data *hexutil.Bytes `json:"data"`
  668. }
  669. // account indicates the overriding fields of account during the execution of
  670. // a message call.
  671. // Note, state and stateDiff can't be specified at the same time. If state is
  672. // set, message execution will only use the data in the given state. Otherwise
  673. // if statDiff is set, all diff will be applied first and then execute the call
  674. // message.
  675. type account struct {
  676. Nonce *hexutil.Uint64 `json:"nonce"`
  677. Code *hexutil.Bytes `json:"code"`
  678. Balance **hexutil.Big `json:"balance"`
  679. State *map[common.Hash]common.Hash `json:"state"`
  680. StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
  681. }
  682. func DoCall(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides map[common.Address]account, vmCfg vm.Config, timeout time.Duration, globalGasCap *big.Int) ([]byte, uint64, bool, error) {
  683. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  684. state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  685. if state == nil || err != nil {
  686. return nil, 0, false, err
  687. }
  688. // Set sender address or use zero address if none specified.
  689. var addr common.Address
  690. if args.From != nil {
  691. addr = *args.From
  692. }
  693. // Override the fields of specified contracts before execution.
  694. for addr, account := range overrides {
  695. // Override account nonce.
  696. if account.Nonce != nil {
  697. state.SetNonce(addr, uint64(*account.Nonce))
  698. }
  699. // Override account(contract) code.
  700. if account.Code != nil {
  701. state.SetCode(addr, *account.Code)
  702. }
  703. // Override account balance.
  704. if account.Balance != nil {
  705. state.SetBalance(addr, (*big.Int)(*account.Balance))
  706. }
  707. if account.State != nil && account.StateDiff != nil {
  708. return nil, 0, false, fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
  709. }
  710. // Replace entire state if caller requires.
  711. if account.State != nil {
  712. state.SetStorage(addr, *account.State)
  713. }
  714. // Apply state diff into specified accounts.
  715. if account.StateDiff != nil {
  716. for key, value := range *account.StateDiff {
  717. state.SetState(addr, key, value)
  718. }
  719. }
  720. }
  721. // Set default gas & gas price if none were set
  722. gas := uint64(math.MaxUint64 / 2)
  723. if args.Gas != nil {
  724. gas = uint64(*args.Gas)
  725. }
  726. if globalGasCap != nil && globalGasCap.Uint64() < gas {
  727. log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
  728. gas = globalGasCap.Uint64()
  729. }
  730. gasPrice := new(big.Int)
  731. if args.GasPrice != nil {
  732. gasPrice = args.GasPrice.ToInt()
  733. }
  734. value := new(big.Int)
  735. if args.Value != nil {
  736. value = args.Value.ToInt()
  737. }
  738. var data []byte
  739. if args.Data != nil {
  740. data = []byte(*args.Data)
  741. }
  742. // Create new call message
  743. msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
  744. // Setup context so it may be cancelled the call has completed
  745. // or, in case of unmetered gas, setup a context with a timeout.
  746. var cancel context.CancelFunc
  747. if timeout > 0 {
  748. ctx, cancel = context.WithTimeout(ctx, timeout)
  749. } else {
  750. ctx, cancel = context.WithCancel(ctx)
  751. }
  752. // Make sure the context is cancelled when the call has completed
  753. // this makes sure resources are cleaned up.
  754. defer cancel()
  755. // Get a new instance of the EVM.
  756. evm, vmError, err := b.GetEVM(ctx, msg, state, header)
  757. if err != nil {
  758. return nil, 0, false, err
  759. }
  760. // Wait for the context to be done and cancel the evm. Even if the
  761. // EVM has finished, cancelling may be done (repeatedly)
  762. go func() {
  763. <-ctx.Done()
  764. evm.Cancel()
  765. }()
  766. // Setup the gas pool (also for unmetered requests)
  767. // and apply the message.
  768. gp := new(core.GasPool).AddGas(math.MaxUint64)
  769. res, gas, failed, err := core.ApplyMessage(evm, msg, gp)
  770. if err := vmError(); err != nil {
  771. return nil, 0, false, err
  772. }
  773. // If the timer caused an abort, return an appropriate error message
  774. if evm.Cancelled() {
  775. return nil, 0, false, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  776. }
  777. return res, gas, failed, err
  778. }
  779. // Call executes the given transaction on the state for the given block number.
  780. //
  781. // Additionally, the caller can specify a batch of contract for fields overriding.
  782. //
  783. // Note, this function doesn't make and changes in the state/blockchain and is
  784. // useful to execute and retrieve values.
  785. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *map[common.Address]account) (hexutil.Bytes, error) {
  786. var accounts map[common.Address]account
  787. if overrides != nil {
  788. accounts = *overrides
  789. }
  790. result, _, _, err := DoCall(ctx, s.b, args, blockNrOrHash, accounts, vm.Config{}, 5*time.Second, s.b.RPCGasCap())
  791. return (hexutil.Bytes)(result), err
  792. }
  793. func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap *big.Int) (hexutil.Uint64, error) {
  794. // Binary search the gas requirement, as it may be higher than the amount used
  795. var (
  796. lo uint64 = params.TxGas - 1
  797. hi uint64
  798. cap uint64
  799. )
  800. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  801. hi = uint64(*args.Gas)
  802. } else {
  803. // Retrieve the block to act as the gas ceiling
  804. block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  805. if err != nil {
  806. return 0, err
  807. }
  808. hi = block.GasLimit()
  809. }
  810. if gasCap != nil && hi > gasCap.Uint64() {
  811. log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  812. hi = gasCap.Uint64()
  813. }
  814. cap = hi
  815. // Use zero address if sender unspecified.
  816. if args.From == nil {
  817. args.From = new(common.Address)
  818. }
  819. // Create a helper to check if a gas allowance results in an executable transaction
  820. executable := func(gas uint64) bool {
  821. args.Gas = (*hexutil.Uint64)(&gas)
  822. _, _, failed, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
  823. if err != nil || failed {
  824. return false
  825. }
  826. return true
  827. }
  828. // Execute the binary search and hone in on an executable gas limit
  829. for lo+1 < hi {
  830. mid := (hi + lo) / 2
  831. if !executable(mid) {
  832. lo = mid
  833. } else {
  834. hi = mid
  835. }
  836. }
  837. // Reject the transaction as invalid if it still fails at the highest allowance
  838. if hi == cap {
  839. if !executable(hi) {
  840. return 0, fmt.Errorf("gas required exceeds allowance (%d) or always failing transaction", cap)
  841. }
  842. }
  843. return hexutil.Uint64(hi), nil
  844. }
  845. // EstimateGas returns an estimate of the amount of gas needed to execute the
  846. // given transaction against the current pending block.
  847. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
  848. blockNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  849. return DoEstimateGas(ctx, s.b, args, blockNrOrHash, s.b.RPCGasCap())
  850. }
  851. // ExecutionResult groups all structured logs emitted by the EVM
  852. // while replaying a transaction in debug mode as well as transaction
  853. // execution status, the amount of gas used and the return value
  854. type ExecutionResult struct {
  855. Gas uint64 `json:"gas"`
  856. Failed bool `json:"failed"`
  857. ReturnValue string `json:"returnValue"`
  858. StructLogs []StructLogRes `json:"structLogs"`
  859. }
  860. // StructLogRes stores a structured log emitted by the EVM while replaying a
  861. // transaction in debug mode
  862. type StructLogRes struct {
  863. Pc uint64 `json:"pc"`
  864. Op string `json:"op"`
  865. Gas uint64 `json:"gas"`
  866. GasCost uint64 `json:"gasCost"`
  867. Depth int `json:"depth"`
  868. Error error `json:"error,omitempty"`
  869. Stack *[]string `json:"stack,omitempty"`
  870. Memory *[]string `json:"memory,omitempty"`
  871. Storage *map[string]string `json:"storage,omitempty"`
  872. }
  873. // FormatLogs formats EVM returned structured logs for json output
  874. func FormatLogs(logs []vm.StructLog) []StructLogRes {
  875. formatted := make([]StructLogRes, len(logs))
  876. for index, trace := range logs {
  877. formatted[index] = StructLogRes{
  878. Pc: trace.Pc,
  879. Op: trace.Op.String(),
  880. Gas: trace.Gas,
  881. GasCost: trace.GasCost,
  882. Depth: trace.Depth,
  883. Error: trace.Err,
  884. }
  885. if trace.Stack != nil {
  886. stack := make([]string, len(trace.Stack))
  887. for i, stackValue := range trace.Stack {
  888. stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  889. }
  890. formatted[index].Stack = &stack
  891. }
  892. if trace.Memory != nil {
  893. memory := make([]string, 0, (len(trace.Memory)+31)/32)
  894. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  895. memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  896. }
  897. formatted[index].Memory = &memory
  898. }
  899. if trace.Storage != nil {
  900. storage := make(map[string]string)
  901. for i, storageValue := range trace.Storage {
  902. storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  903. }
  904. formatted[index].Storage = &storage
  905. }
  906. }
  907. return formatted
  908. }
  909. // RPCMarshalHeader converts the given header to the RPC output .
  910. func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  911. return map[string]interface{}{
  912. "number": (*hexutil.Big)(head.Number),
  913. "hash": head.Hash(),
  914. "parentHash": head.ParentHash,
  915. "nonce": head.Nonce,
  916. "mixHash": head.MixDigest,
  917. "sha3Uncles": head.UncleHash,
  918. "logsBloom": head.Bloom,
  919. "stateRoot": head.Root,
  920. "miner": head.Coinbase,
  921. "difficulty": (*hexutil.Big)(head.Difficulty),
  922. "extraData": hexutil.Bytes(head.Extra),
  923. "size": hexutil.Uint64(head.Size()),
  924. "gasLimit": hexutil.Uint64(head.GasLimit),
  925. "gasUsed": hexutil.Uint64(head.GasUsed),
  926. "timestamp": hexutil.Uint64(head.Time),
  927. "transactionsRoot": head.TxHash,
  928. "receiptsRoot": head.ReceiptHash,
  929. }
  930. }
  931. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  932. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  933. // transaction hashes.
  934. func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  935. fields := RPCMarshalHeader(block.Header())
  936. fields["size"] = hexutil.Uint64(block.Size())
  937. if inclTx {
  938. formatTx := func(tx *types.Transaction) (interface{}, error) {
  939. return tx.Hash(), nil
  940. }
  941. if fullTx {
  942. formatTx = func(tx *types.Transaction) (interface{}, error) {
  943. return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  944. }
  945. }
  946. txs := block.Transactions()
  947. transactions := make([]interface{}, len(txs))
  948. var err error
  949. for i, tx := range txs {
  950. if transactions[i], err = formatTx(tx); err != nil {
  951. return nil, err
  952. }
  953. }
  954. fields["transactions"] = transactions
  955. }
  956. uncles := block.Uncles()
  957. uncleHashes := make([]common.Hash, len(uncles))
  958. for i, uncle := range uncles {
  959. uncleHashes[i] = uncle.Hash()
  960. }
  961. fields["uncles"] = uncleHashes
  962. return fields, nil
  963. }
  964. // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  965. // a `PublicBlockchainAPI`.
  966. func (s *PublicBlockChainAPI) rpcMarshalHeader(header *types.Header) map[string]interface{} {
  967. fields := RPCMarshalHeader(header)
  968. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(header.Hash()))
  969. return fields
  970. }
  971. // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  972. // a `PublicBlockchainAPI`.
  973. func (s *PublicBlockChainAPI) rpcMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  974. fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  975. if err != nil {
  976. return nil, err
  977. }
  978. if inclTx {
  979. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash()))
  980. }
  981. return fields, err
  982. }
  983. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  984. type RPCTransaction struct {
  985. BlockHash *common.Hash `json:"blockHash"`
  986. BlockNumber *hexutil.Big `json:"blockNumber"`
  987. From common.Address `json:"from"`
  988. Gas hexutil.Uint64 `json:"gas"`
  989. GasPrice *hexutil.Big `json:"gasPrice"`
  990. Hash common.Hash `json:"hash"`
  991. Input hexutil.Bytes `json:"input"`
  992. Nonce hexutil.Uint64 `json:"nonce"`
  993. To *common.Address `json:"to"`
  994. TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  995. Value *hexutil.Big `json:"value"`
  996. V *hexutil.Big `json:"v"`
  997. R *hexutil.Big `json:"r"`
  998. S *hexutil.Big `json:"s"`
  999. }
  1000. // newRPCTransaction returns a transaction that will serialize to the RPC
  1001. // representation, with the given location metadata set (if available).
  1002. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1003. var signer types.Signer = types.FrontierSigner{}
  1004. if tx.Protected() {
  1005. signer = types.NewEIP155Signer(tx.ChainId())
  1006. }
  1007. from, _ := types.Sender(signer, tx)
  1008. v, r, s := tx.RawSignatureValues()
  1009. result := &RPCTransaction{
  1010. From: from,
  1011. Gas: hexutil.Uint64(tx.Gas()),
  1012. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1013. Hash: tx.Hash(),
  1014. Input: hexutil.Bytes(tx.Data()),
  1015. Nonce: hexutil.Uint64(tx.Nonce()),
  1016. To: tx.To(),
  1017. Value: (*hexutil.Big)(tx.Value()),
  1018. V: (*hexutil.Big)(v),
  1019. R: (*hexutil.Big)(r),
  1020. S: (*hexutil.Big)(s),
  1021. }
  1022. if blockHash != (common.Hash{}) {
  1023. result.BlockHash = &blockHash
  1024. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1025. result.TransactionIndex = (*hexutil.Uint64)(&index)
  1026. }
  1027. return result
  1028. }
  1029. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1030. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1031. return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1032. }
  1033. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1034. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1035. txs := b.Transactions()
  1036. if index >= uint64(len(txs)) {
  1037. return nil
  1038. }
  1039. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1040. }
  1041. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1042. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1043. txs := b.Transactions()
  1044. if index >= uint64(len(txs)) {
  1045. return nil
  1046. }
  1047. blob, _ := rlp.EncodeToBytes(txs[index])
  1048. return blob
  1049. }
  1050. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1051. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1052. for idx, tx := range b.Transactions() {
  1053. if tx.Hash() == hash {
  1054. return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1055. }
  1056. }
  1057. return nil
  1058. }
  1059. // PublicTransactionPoolAPI exposes methods for the RPC interface
  1060. type PublicTransactionPoolAPI struct {
  1061. b Backend
  1062. nonceLock *AddrLocker
  1063. }
  1064. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1065. func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1066. return &PublicTransactionPoolAPI{b, nonceLock}
  1067. }
  1068. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1069. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1070. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1071. n := hexutil.Uint(len(block.Transactions()))
  1072. return &n
  1073. }
  1074. return nil
  1075. }
  1076. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1077. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1078. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1079. n := hexutil.Uint(len(block.Transactions()))
  1080. return &n
  1081. }
  1082. return nil
  1083. }
  1084. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1085. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1086. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1087. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1088. }
  1089. return nil
  1090. }
  1091. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1092. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1093. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1094. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1095. }
  1096. return nil
  1097. }
  1098. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1099. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1100. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1101. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1102. }
  1103. return nil
  1104. }
  1105. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1106. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1107. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1108. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1109. }
  1110. return nil
  1111. }
  1112. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1113. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1114. // Ask transaction pool for the nonce which includes pending transactions
  1115. if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1116. nonce, err := s.b.GetPoolNonce(ctx, address)
  1117. if err != nil {
  1118. return nil, err
  1119. }
  1120. return (*hexutil.Uint64)(&nonce), nil
  1121. }
  1122. // Resolve block number and use its state to ask for the nonce
  1123. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1124. if state == nil || err != nil {
  1125. return nil, err
  1126. }
  1127. nonce := state.GetNonce(address)
  1128. return (*hexutil.Uint64)(&nonce), state.Error()
  1129. }
  1130. // GetTransactionByHash returns the transaction for the given hash
  1131. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1132. // Try to return an already finalized transaction
  1133. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1134. if err != nil {
  1135. return nil, err
  1136. }
  1137. if tx != nil {
  1138. return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1139. }
  1140. // No finalized transaction, try to retrieve it from the pool
  1141. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1142. return newRPCPendingTransaction(tx), nil
  1143. }
  1144. // Transaction unknown, return as such
  1145. return nil, nil
  1146. }
  1147. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1148. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1149. // Retrieve a finalized transaction, or a pooled otherwise
  1150. tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1151. if err != nil {
  1152. return nil, err
  1153. }
  1154. if tx == nil {
  1155. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1156. // Transaction not found anywhere, abort
  1157. return nil, nil
  1158. }
  1159. }
  1160. // Serialize to RLP and return
  1161. return rlp.EncodeToBytes(tx)
  1162. }
  1163. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1164. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1165. tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1166. if tx == nil {
  1167. return nil, nil
  1168. }
  1169. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1170. if err != nil {
  1171. return nil, err
  1172. }
  1173. if len(receipts) <= int(index) {
  1174. return nil, nil
  1175. }
  1176. receipt := receipts[index]
  1177. var signer types.Signer = types.FrontierSigner{}
  1178. if tx.Protected() {
  1179. signer = types.NewEIP155Signer(tx.ChainId())
  1180. }
  1181. from, _ := types.Sender(signer, tx)
  1182. fields := map[string]interface{}{
  1183. "blockHash": blockHash,
  1184. "blockNumber": hexutil.Uint64(blockNumber),
  1185. "transactionHash": hash,
  1186. "transactionIndex": hexutil.Uint64(index),
  1187. "from": from,
  1188. "to": tx.To(),
  1189. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1190. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1191. "contractAddress": nil,
  1192. "logs": receipt.Logs,
  1193. "logsBloom": receipt.Bloom,
  1194. }
  1195. // Assign receipt status or post state.
  1196. if len(receipt.PostState) > 0 {
  1197. fields["root"] = hexutil.Bytes(receipt.PostState)
  1198. } else {
  1199. fields["status"] = hexutil.Uint(receipt.Status)
  1200. }
  1201. if receipt.Logs == nil {
  1202. fields["logs"] = [][]*types.Log{}
  1203. }
  1204. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1205. if receipt.ContractAddress != (common.Address{}) {
  1206. fields["contractAddress"] = receipt.ContractAddress
  1207. }
  1208. return fields, nil
  1209. }
  1210. // sign is a helper function that signs a transaction with the private key of the given address.
  1211. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1212. // Look up the wallet containing the requested signer
  1213. account := accounts.Account{Address: addr}
  1214. wallet, err := s.b.AccountManager().Find(account)
  1215. if err != nil {
  1216. return nil, err
  1217. }
  1218. // Request the wallet to sign the transaction
  1219. return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1220. }
  1221. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1222. type SendTxArgs struct {
  1223. From common.Address `json:"from"`
  1224. To *common.Address `json:"to"`
  1225. Gas *hexutil.Uint64 `json:"gas"`
  1226. GasPrice *hexutil.Big `json:"gasPrice"`
  1227. Value *hexutil.Big `json:"value"`
  1228. Nonce *hexutil.Uint64 `json:"nonce"`
  1229. // We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1230. // newer name and should be preferred by clients.
  1231. Data *hexutil.Bytes `json:"data"`
  1232. Input *hexutil.Bytes `json:"input"`
  1233. }
  1234. // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1235. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1236. if args.GasPrice == nil {
  1237. price, err := b.SuggestPrice(ctx)
  1238. if err != nil {
  1239. return err
  1240. }
  1241. args.GasPrice = (*hexutil.Big)(price)
  1242. }
  1243. if args.Value == nil {
  1244. args.Value = new(hexutil.Big)
  1245. }
  1246. if args.Nonce == nil {
  1247. nonce, err := b.GetPoolNonce(ctx, args.From)
  1248. if err != nil {
  1249. return err
  1250. }
  1251. args.Nonce = (*hexutil.Uint64)(&nonce)
  1252. }
  1253. if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1254. return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
  1255. }
  1256. if args.To == nil {
  1257. // Contract creation
  1258. var input []byte
  1259. if args.Data != nil {
  1260. input = *args.Data
  1261. } else if args.Input != nil {
  1262. input = *args.Input
  1263. }
  1264. if len(input) == 0 {
  1265. return errors.New(`contract creation without any data provided`)
  1266. }
  1267. }
  1268. // Estimate the gas usage if necessary.
  1269. if args.Gas == nil {
  1270. // For backwards-compatibility reason, we try both input and data
  1271. // but input is preferred.
  1272. input := args.Input
  1273. if input == nil {
  1274. input = args.Data
  1275. }
  1276. callArgs := CallArgs{
  1277. From: &args.From, // From shouldn't be nil
  1278. To: args.To,
  1279. GasPrice: args.GasPrice,
  1280. Value: args.Value,
  1281. Data: input,
  1282. }
  1283. pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1284. estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1285. if err != nil {
  1286. return err
  1287. }
  1288. args.Gas = &estimated
  1289. log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1290. }
  1291. return nil
  1292. }
  1293. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1294. var input []byte
  1295. if args.Input != nil {
  1296. input = *args.Input
  1297. } else if args.Data != nil {
  1298. input = *args.Data
  1299. }
  1300. if args.To == nil {
  1301. return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1302. }
  1303. return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1304. }
  1305. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1306. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1307. if err := b.SendTx(ctx, tx); err != nil {
  1308. return common.Hash{}, err
  1309. }
  1310. if tx.To() == nil {
  1311. signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1312. from, err := types.Sender(signer, tx)
  1313. if err != nil {
  1314. return common.Hash{}, err
  1315. }
  1316. addr := crypto.CreateAddress(from, tx.Nonce())
  1317. log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1318. } else {
  1319. log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1320. }
  1321. return tx.Hash(), nil
  1322. }
  1323. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1324. // transaction pool.
  1325. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1326. // Look up the wallet containing the requested signer
  1327. account := accounts.Account{Address: args.From}
  1328. wallet, err := s.b.AccountManager().Find(account)
  1329. if err != nil {
  1330. return common.Hash{}, err
  1331. }
  1332. if args.Nonce == nil {
  1333. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  1334. // the same nonce to multiple accounts.
  1335. s.nonceLock.LockAddr(args.From)
  1336. defer s.nonceLock.UnlockAddr(args.From)
  1337. }
  1338. // Set some sanity defaults and terminate on failure
  1339. if err := args.setDefaults(ctx, s.b); err != nil {
  1340. return common.Hash{}, err
  1341. }
  1342. // Assemble the transaction and sign with the wallet
  1343. tx := args.toTransaction()
  1344. signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1345. if err != nil {
  1346. return common.Hash{}, err
  1347. }
  1348. return SubmitTransaction(ctx, s.b, signed)
  1349. }
  1350. // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  1351. // and returns it to the caller for further processing (signing + broadcast)
  1352. func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1353. // Set some sanity defaults and terminate on failure
  1354. if err := args.setDefaults(ctx, s.b); err != nil {
  1355. return nil, err
  1356. }
  1357. // Assemble the transaction and obtain rlp
  1358. tx := args.toTransaction()
  1359. data, err := rlp.EncodeToBytes(tx)
  1360. if err != nil {
  1361. return nil, err
  1362. }
  1363. return &SignTransactionResult{data, tx}, nil
  1364. }
  1365. // SendRawTransaction will add the signed transaction to the transaction pool.
  1366. // The sender is responsible for signing the transaction and using the correct nonce.
  1367. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1368. tx := new(types.Transaction)
  1369. if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1370. return common.Hash{}, err
  1371. }
  1372. return SubmitTransaction(ctx, s.b, tx)
  1373. }
  1374. // Sign calculates an ECDSA signature for:
  1375. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1376. //
  1377. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1378. // where the V value will be 27 or 28 for legacy reasons.
  1379. //
  1380. // The account associated with addr must be unlocked.
  1381. //
  1382. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1383. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1384. // Look up the wallet containing the requested signer
  1385. account := accounts.Account{Address: addr}
  1386. wallet, err := s.b.AccountManager().Find(account)
  1387. if err != nil {
  1388. return nil, err
  1389. }
  1390. // Sign the requested hash with the wallet
  1391. signature, err := wallet.SignText(account, data)
  1392. if err == nil {
  1393. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1394. }
  1395. return signature, err
  1396. }
  1397. // SignTransactionResult represents a RLP encoded signed transaction.
  1398. type SignTransactionResult struct {
  1399. Raw hexutil.Bytes `json:"raw"`
  1400. Tx *types.Transaction `json:"tx"`
  1401. }
  1402. // SignTransaction will sign the given transaction with the from account.
  1403. // The node needs to have the private key of the account corresponding with
  1404. // the given from address and it needs to be unlocked.
  1405. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1406. if args.Gas == nil {
  1407. return nil, fmt.Errorf("gas not specified")
  1408. }
  1409. if args.GasPrice == nil {
  1410. return nil, fmt.Errorf("gasPrice not specified")
  1411. }
  1412. if args.Nonce == nil {
  1413. return nil, fmt.Errorf("nonce not specified")
  1414. }
  1415. if err := args.setDefaults(ctx, s.b); err != nil {
  1416. return nil, err
  1417. }
  1418. tx, err := s.sign(args.From, args.toTransaction())
  1419. if err != nil {
  1420. return nil, err
  1421. }
  1422. data, err := rlp.EncodeToBytes(tx)
  1423. if err != nil {
  1424. return nil, err
  1425. }
  1426. return &SignTransactionResult{data, tx}, nil
  1427. }
  1428. // PendingTransactions returns the transactions that are in the transaction pool
  1429. // and have a from address that is one of the accounts this node manages.
  1430. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1431. pending, err := s.b.GetPoolTransactions()
  1432. if err != nil {
  1433. return nil, err
  1434. }
  1435. accounts := make(map[common.Address]struct{})
  1436. for _, wallet := range s.b.AccountManager().Wallets() {
  1437. for _, account := range wallet.Accounts() {
  1438. accounts[account.Address] = struct{}{}
  1439. }
  1440. }
  1441. transactions := make([]*RPCTransaction, 0, len(pending))
  1442. for _, tx := range pending {
  1443. var signer types.Signer = types.HomesteadSigner{}
  1444. if tx.Protected() {
  1445. signer = types.NewEIP155Signer(tx.ChainId())
  1446. }
  1447. from, _ := types.Sender(signer, tx)
  1448. if _, exists := accounts[from]; exists {
  1449. transactions = append(transactions, newRPCPendingTransaction(tx))
  1450. }
  1451. }
  1452. return transactions, nil
  1453. }
  1454. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1455. // the given transaction from the pool and reinsert it with the new gas price and limit.
  1456. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1457. if sendArgs.Nonce == nil {
  1458. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1459. }
  1460. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1461. return common.Hash{}, err
  1462. }
  1463. matchTx := sendArgs.toTransaction()
  1464. pending, err := s.b.GetPoolTransactions()
  1465. if err != nil {
  1466. return common.Hash{}, err
  1467. }
  1468. for _, p := range pending {
  1469. var signer types.Signer = types.HomesteadSigner{}
  1470. if p.Protected() {
  1471. signer = types.NewEIP155Signer(p.ChainId())
  1472. }
  1473. wantSigHash := signer.Hash(matchTx)
  1474. if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1475. // Match. Re-sign and send the transaction.
  1476. if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1477. sendArgs.GasPrice = gasPrice
  1478. }
  1479. if gasLimit != nil && *gasLimit != 0 {
  1480. sendArgs.Gas = gasLimit
  1481. }
  1482. signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1483. if err != nil {
  1484. return common.Hash{}, err
  1485. }
  1486. if err = s.b.SendTx(ctx, signedTx); err != nil {
  1487. return common.Hash{}, err
  1488. }
  1489. return signedTx.Hash(), nil
  1490. }
  1491. }
  1492. return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  1493. }
  1494. // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1495. // debugging endpoint.
  1496. type PublicDebugAPI struct {
  1497. b Backend
  1498. }
  1499. // NewPublicDebugAPI creates a new API definition for the public debug methods
  1500. // of the Ethereum service.
  1501. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1502. return &PublicDebugAPI{b: b}
  1503. }
  1504. // GetBlockRlp retrieves the RLP encoded for of a single block.
  1505. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1506. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1507. if block == nil {
  1508. return "", fmt.Errorf("block #%d not found", number)
  1509. }
  1510. encoded, err := rlp.EncodeToBytes(block)
  1511. if err != nil {
  1512. return "", err
  1513. }
  1514. return fmt.Sprintf("%x", encoded), nil
  1515. }
  1516. // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  1517. // given address, returning the address of the recovered signature
  1518. //
  1519. // This is a temporary method to debug the externalsigner integration,
  1520. // TODO: Remove this method when the integration is mature
  1521. func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  1522. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1523. if block == nil {
  1524. return common.Address{}, fmt.Errorf("block #%d not found", number)
  1525. }
  1526. header := block.Header()
  1527. header.Extra = make([]byte, 32+65)
  1528. encoded := clique.CliqueRLP(header)
  1529. // Look up the wallet containing the requested signer
  1530. account := accounts.Account{Address: address}
  1531. wallet, err := api.b.AccountManager().Find(account)
  1532. if err != nil {
  1533. return common.Address{}, err
  1534. }
  1535. signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  1536. if err != nil {
  1537. return common.Address{}, err
  1538. }
  1539. sealHash := clique.SealHash(header).Bytes()
  1540. log.Info("test signing of clique block",
  1541. "Sealhash", fmt.Sprintf("%x", sealHash),
  1542. "signature", fmt.Sprintf("%x", signature))
  1543. pubkey, err := crypto.Ecrecover(sealHash, signature)
  1544. if err != nil {
  1545. return common.Address{}, err
  1546. }
  1547. var signer common.Address
  1548. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  1549. return signer, nil
  1550. }
  1551. // PrintBlock retrieves a block and returns its pretty printed form.
  1552. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1553. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1554. if block == nil {
  1555. return "", fmt.Errorf("block #%d not found", number)
  1556. }
  1557. return spew.Sdump(block), nil
  1558. }
  1559. // SeedHash retrieves the seed hash of a block.
  1560. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1561. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1562. if block == nil {
  1563. return "", fmt.Errorf("block #%d not found", number)
  1564. }
  1565. return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1566. }
  1567. // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1568. // debugging endpoint.
  1569. type PrivateDebugAPI struct {
  1570. b Backend
  1571. }
  1572. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1573. // of the Ethereum service.
  1574. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1575. return &PrivateDebugAPI{b: b}
  1576. }
  1577. // ChaindbProperty returns leveldb properties of the key-value database.
  1578. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1579. if property == "" {
  1580. property = "leveldb.stats"
  1581. } else if !strings.HasPrefix(property, "leveldb.") {
  1582. property = "leveldb." + property
  1583. }
  1584. return api.b.ChainDb().Stat(property)
  1585. }
  1586. // ChaindbCompact flattens the entire key-value database into a single level,
  1587. // removing all unused slots and merging all keys.
  1588. func (api *PrivateDebugAPI) ChaindbCompact() error {
  1589. for b := byte(0); b < 255; b++ {
  1590. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1591. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1592. log.Error("Database compaction failed", "err", err)
  1593. return err
  1594. }
  1595. }
  1596. return nil
  1597. }
  1598. // SetHead rewinds the head of the blockchain to a previous block.
  1599. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1600. api.b.SetHead(uint64(number))
  1601. }
  1602. // PublicNetAPI offers network related RPC methods
  1603. type PublicNetAPI struct {
  1604. net *p2p.Server
  1605. networkVersion uint64
  1606. }
  1607. // NewPublicNetAPI creates a new net API instance.
  1608. func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1609. return &PublicNetAPI{net, networkVersion}
  1610. }
  1611. // Listening returns an indication if the node is listening for network connections.
  1612. func (s *PublicNetAPI) Listening() bool {
  1613. return true // always listening
  1614. }
  1615. // PeerCount returns the number of connected peers
  1616. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1617. return hexutil.Uint(s.net.PeerCount())
  1618. }
  1619. // Version returns the current ethereum protocol version.
  1620. func (s *PublicNetAPI) Version() string {
  1621. return fmt.Sprintf("%d", s.networkVersion)
  1622. }