api.go 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  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. "encoding/base64"
  21. "encoding/hex"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "math/big"
  26. "net/http"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/davecgh/go-spew/spew"
  31. "github.com/ethereum/go-ethereum/accounts"
  32. "github.com/ethereum/go-ethereum/accounts/abi"
  33. "github.com/ethereum/go-ethereum/accounts/keystore"
  34. "github.com/ethereum/go-ethereum/accounts/pluggable"
  35. "github.com/ethereum/go-ethereum/accounts/scwallet"
  36. "github.com/ethereum/go-ethereum/common"
  37. "github.com/ethereum/go-ethereum/common/hexutil"
  38. "github.com/ethereum/go-ethereum/common/math"
  39. "github.com/ethereum/go-ethereum/consensus/clique"
  40. "github.com/ethereum/go-ethereum/consensus/ethash"
  41. "github.com/ethereum/go-ethereum/core"
  42. "github.com/ethereum/go-ethereum/core/mps"
  43. "github.com/ethereum/go-ethereum/core/state"
  44. "github.com/ethereum/go-ethereum/core/types"
  45. "github.com/ethereum/go-ethereum/core/vm"
  46. "github.com/ethereum/go-ethereum/crypto"
  47. "github.com/ethereum/go-ethereum/log"
  48. "github.com/ethereum/go-ethereum/multitenancy"
  49. "github.com/ethereum/go-ethereum/p2p"
  50. "github.com/ethereum/go-ethereum/params"
  51. "github.com/ethereum/go-ethereum/private"
  52. "github.com/ethereum/go-ethereum/private/engine"
  53. "github.com/ethereum/go-ethereum/rlp"
  54. "github.com/ethereum/go-ethereum/rpc"
  55. "github.com/tyler-smith/go-bip39"
  56. )
  57. type TransactionType uint8
  58. const (
  59. FillTransaction TransactionType = iota + 1
  60. RawTransaction
  61. NormalTransaction
  62. )
  63. // PublicEthereumAPI provides an API to access Ethereum related information.
  64. // It offers only methods that operate on public data that is freely available to anyone.
  65. type PublicEthereumAPI struct {
  66. b Backend
  67. }
  68. // NewPublicEthereumAPI creates a new Ethereum protocol API.
  69. func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
  70. return &PublicEthereumAPI{b}
  71. }
  72. // GasPrice returns a suggestion for a gas price.
  73. func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
  74. price, err := s.b.SuggestPrice(ctx)
  75. return (*hexutil.Big)(price), err
  76. }
  77. // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
  78. // yet received the latest block headers from its pears. In case it is synchronizing:
  79. // - startingBlock: block number this node started to synchronise from
  80. // - currentBlock: block number this node is currently importing
  81. // - highestBlock: block number of the highest block header this node has received from peers
  82. // - pulledStates: number of state entries processed until now
  83. // - knownStates: number of known state entries that still need to be pulled
  84. func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
  85. progress := s.b.Downloader().Progress()
  86. // Return not syncing if the synchronisation already completed
  87. if progress.CurrentBlock >= progress.HighestBlock {
  88. return false, nil
  89. }
  90. // Otherwise gather the block sync stats
  91. return map[string]interface{}{
  92. "startingBlock": hexutil.Uint64(progress.StartingBlock),
  93. "currentBlock": hexutil.Uint64(progress.CurrentBlock),
  94. "highestBlock": hexutil.Uint64(progress.HighestBlock),
  95. "pulledStates": hexutil.Uint64(progress.PulledStates),
  96. "knownStates": hexutil.Uint64(progress.KnownStates),
  97. }, nil
  98. }
  99. func (s *PublicEthereumAPI) GetPrivacyPrecompileAddress() common.Address {
  100. return common.QuorumPrivacyPrecompileContractAddress()
  101. }
  102. // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
  103. type PublicTxPoolAPI struct {
  104. b Backend
  105. }
  106. // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
  107. func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
  108. return &PublicTxPoolAPI{b}
  109. }
  110. // Content returns the transactions contained within the transaction pool.
  111. func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
  112. content := map[string]map[string]map[string]*RPCTransaction{
  113. "pending": make(map[string]map[string]*RPCTransaction),
  114. "queued": make(map[string]map[string]*RPCTransaction),
  115. }
  116. pending, queue := s.b.TxPoolContent()
  117. // Flatten the pending transactions
  118. for account, txs := range pending {
  119. dump := make(map[string]*RPCTransaction)
  120. for _, tx := range txs {
  121. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
  122. }
  123. content["pending"][account.Hex()] = dump
  124. }
  125. // Flatten the queued transactions
  126. for account, txs := range queue {
  127. dump := make(map[string]*RPCTransaction)
  128. for _, tx := range txs {
  129. dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
  130. }
  131. content["queued"][account.Hex()] = dump
  132. }
  133. return content
  134. }
  135. // Status returns the number of pending and queued transaction in the pool.
  136. func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
  137. pending, queue := s.b.Stats()
  138. return map[string]hexutil.Uint{
  139. "pending": hexutil.Uint(pending),
  140. "queued": hexutil.Uint(queue),
  141. }
  142. }
  143. // Inspect retrieves the content of the transaction pool and flattens it into an
  144. // easily inspectable list.
  145. func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
  146. content := map[string]map[string]map[string]string{
  147. "pending": make(map[string]map[string]string),
  148. "queued": make(map[string]map[string]string),
  149. }
  150. pending, queue := s.b.TxPoolContent()
  151. // Define a formatter to flatten a transaction into a string
  152. var format = func(tx *types.Transaction) string {
  153. if to := tx.To(); to != nil {
  154. return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
  155. }
  156. return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
  157. }
  158. // Flatten the pending transactions
  159. for account, txs := range pending {
  160. dump := make(map[string]string)
  161. for _, tx := range txs {
  162. dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
  163. }
  164. content["pending"][account.Hex()] = dump
  165. }
  166. // Flatten the queued transactions
  167. for account, txs := range queue {
  168. dump := make(map[string]string)
  169. for _, tx := range txs {
  170. dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
  171. }
  172. content["queued"][account.Hex()] = dump
  173. }
  174. return content
  175. }
  176. // PublicAccountAPI provides an API to access accounts managed by this node.
  177. // It offers only methods that can retrieve accounts.
  178. type PublicAccountAPI struct {
  179. am *accounts.Manager
  180. }
  181. // NewPublicAccountAPI creates a new PublicAccountAPI.
  182. func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
  183. return &PublicAccountAPI{am: am}
  184. }
  185. // Accounts returns the collection of accounts this node manages
  186. func (s *PublicAccountAPI) Accounts() []common.Address {
  187. return s.am.Accounts()
  188. }
  189. // PrivateAccountAPI provides an API to access accounts managed by this node.
  190. // It offers methods to create, (un)lock en list accounts. Some methods accept
  191. // passwords and are therefore considered private by default.
  192. type PrivateAccountAPI struct {
  193. am *accounts.Manager
  194. nonceLock *AddrLocker
  195. b Backend
  196. }
  197. // NewPrivateAccountAPI create a new PrivateAccountAPI.
  198. func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
  199. return &PrivateAccountAPI{
  200. am: b.AccountManager(),
  201. nonceLock: nonceLock,
  202. b: b,
  203. }
  204. }
  205. // listAccounts will return a list of addresses for accounts this node manages.
  206. func (s *PrivateAccountAPI) ListAccounts() []common.Address {
  207. return s.am.Accounts()
  208. }
  209. // rawWallet is a JSON representation of an accounts.Wallet interface, with its
  210. // data contents extracted into plain fields.
  211. type rawWallet struct {
  212. URL string `json:"url"`
  213. Status string `json:"status"`
  214. Failure string `json:"failure,omitempty"`
  215. Accounts []accounts.Account `json:"accounts,omitempty"`
  216. }
  217. // ListWallets will return a list of wallets this node manages.
  218. func (s *PrivateAccountAPI) ListWallets() []rawWallet {
  219. wallets := make([]rawWallet, 0) // return [] instead of nil if empty
  220. for _, wallet := range s.am.Wallets() {
  221. status, failure := wallet.Status()
  222. raw := rawWallet{
  223. URL: wallet.URL().String(),
  224. Status: status,
  225. Accounts: wallet.Accounts(),
  226. }
  227. if failure != nil {
  228. raw.Failure = failure.Error()
  229. }
  230. wallets = append(wallets, raw)
  231. }
  232. return wallets
  233. }
  234. // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
  235. // connection and attempting to authenticate via the provided passphrase. Note,
  236. // the method may return an extra challenge requiring a second open (e.g. the
  237. // Trezor PIN matrix challenge).
  238. func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
  239. wallet, err := s.am.Wallet(url)
  240. if err != nil {
  241. return err
  242. }
  243. pass := ""
  244. if passphrase != nil {
  245. pass = *passphrase
  246. }
  247. return wallet.Open(pass)
  248. }
  249. // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
  250. // it for later reuse.
  251. func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
  252. wallet, err := s.am.Wallet(url)
  253. if err != nil {
  254. return accounts.Account{}, err
  255. }
  256. derivPath, err := accounts.ParseDerivationPath(path)
  257. if err != nil {
  258. return accounts.Account{}, err
  259. }
  260. if pin == nil {
  261. pin = new(bool)
  262. }
  263. return wallet.Derive(derivPath, *pin)
  264. }
  265. // NewAccount will create a new account and returns the address for the new account.
  266. func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
  267. ks, err := fetchKeystore(s.am)
  268. if err != nil {
  269. return common.Address{}, err
  270. }
  271. acc, err := ks.NewAccount(password)
  272. if err == nil {
  273. log.Info("Your new key was generated", "address", acc.Address)
  274. log.Warn("Please backup your key file!", "path", acc.URL.Path)
  275. log.Warn("Please remember your password!")
  276. return acc.Address, nil
  277. }
  278. return common.Address{}, err
  279. }
  280. // fetchKeystore retrieves the encrypted keystore from the account manager.
  281. func fetchKeystore(am *accounts.Manager) (*keystore.KeyStore, error) {
  282. if ks := am.Backends(keystore.KeyStoreType); len(ks) > 0 {
  283. return ks[0].(*keystore.KeyStore), nil
  284. }
  285. return nil, errors.New("local keystore not used")
  286. }
  287. // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
  288. // encrypting it with the passphrase.
  289. func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
  290. key, err := crypto.HexToECDSA(privkey)
  291. if err != nil {
  292. return common.Address{}, err
  293. }
  294. ks, err := fetchKeystore(s.am)
  295. if err != nil {
  296. return common.Address{}, err
  297. }
  298. acc, err := ks.ImportECDSA(key, password)
  299. return acc.Address, err
  300. }
  301. // UnlockAccount will unlock the account associated with the given address with
  302. // the given password for duration seconds. If duration is nil it will use a
  303. // default of 300 seconds. It returns an indication if the account was unlocked.
  304. func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
  305. // When the API is exposed by external RPC(http, ws etc), unless the user
  306. // explicitly specifies to allow the insecure account unlocking, otherwise
  307. // it is disabled.
  308. if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed {
  309. return false, errors.New("account unlock with HTTP access is forbidden")
  310. }
  311. const max = uint64(time.Duration(math.MaxInt64) / time.Second)
  312. var d time.Duration
  313. if duration == nil {
  314. d = 300 * time.Second
  315. } else if *duration > max {
  316. return false, errors.New("unlock duration too large")
  317. } else {
  318. d = time.Duration(*duration) * time.Second
  319. }
  320. err := s.unlockAccount(addr, password, d)
  321. if err != nil {
  322. log.Warn("Failed account unlock attempt", "address", addr, "err", err)
  323. }
  324. return err == nil, err
  325. }
  326. func (s *PrivateAccountAPI) unlockAccount(addr common.Address, password string, duration time.Duration) error {
  327. acct := accounts.Account{Address: addr}
  328. backend, err := s.am.Backend(acct)
  329. if err != nil {
  330. return err
  331. }
  332. switch b := backend.(type) {
  333. case *pluggable.Backend:
  334. return b.TimedUnlock(acct, password, duration)
  335. case *keystore.KeyStore:
  336. return b.TimedUnlock(acct, password, duration)
  337. default:
  338. return errors.New("unlock only supported for keystore or plugin wallets")
  339. }
  340. }
  341. // LockAccount will lock the account associated with the given address when it's unlocked.
  342. func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
  343. if err := s.lockAccount(addr); err != nil {
  344. log.Warn("Failed account lock attempt", "address", addr, "err", err)
  345. return false
  346. }
  347. return true
  348. }
  349. func (s *PrivateAccountAPI) lockAccount(addr common.Address) error {
  350. acct := accounts.Account{Address: addr}
  351. backend, err := s.am.Backend(acct)
  352. if err != nil {
  353. return err
  354. }
  355. switch b := backend.(type) {
  356. case *pluggable.Backend:
  357. return b.Lock(acct)
  358. case *keystore.KeyStore:
  359. return b.Lock(addr)
  360. default:
  361. return errors.New("lock only supported for keystore or plugin wallets")
  362. }
  363. }
  364. // signTransaction sets defaults and signs the given transaction
  365. // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
  366. // and release it after the transaction has been submitted to the tx pool
  367. func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) {
  368. // Look up the wallet containing the requested signer
  369. account := accounts.Account{Address: args.From}
  370. wallet, err := s.am.Find(account)
  371. if err != nil {
  372. return nil, err
  373. }
  374. // Set some sanity defaults and terminate on failure
  375. if err := args.setDefaults(ctx, s.b); err != nil {
  376. return nil, err
  377. }
  378. // Assemble the transaction and sign with the wallet
  379. tx := args.toTransaction()
  380. // Quorum
  381. if args.IsPrivate() {
  382. tx.SetPrivate()
  383. }
  384. var chainID *big.Int
  385. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  386. chainID = config.ChainID
  387. }
  388. // /Quorum
  389. return wallet.SignTxWithPassphrase(account, passwd, tx, chainID)
  390. }
  391. // SendTransaction will create a transaction from the given arguments and
  392. // tries to sign it with the key associated with args.From. If the given passwd isn't
  393. // able to decrypt the key it fails.
  394. func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  395. if args.Nonce == nil {
  396. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  397. // the same nonce to multiple accounts.
  398. s.nonceLock.LockAddr(args.From)
  399. defer s.nonceLock.UnlockAddr(args.From)
  400. }
  401. // Set some sanity defaults and terminate on failure
  402. if err := args.setDefaults(ctx, s.b); err != nil {
  403. return common.Hash{}, err
  404. }
  405. // Quorum
  406. _, replaceDataWithHash, data, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, NormalTransaction)
  407. if err != nil {
  408. return common.Hash{}, err
  409. }
  410. if replaceDataWithHash {
  411. // replace the original payload with encrypted payload hash
  412. args.Data = data.BytesTypeRef()
  413. }
  414. // /Quorum
  415. signed, err := s.signTransaction(ctx, &args, passwd)
  416. if err != nil {
  417. log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  418. return common.Hash{}, err
  419. }
  420. // Quorum
  421. if signed.IsPrivate() && s.b.IsPrivacyMarkerTransactionCreationEnabled() {
  422. // Look up the wallet containing the requested signer
  423. account := accounts.Account{Address: args.From}
  424. wallet, err := s.am.Find(account)
  425. if err != nil {
  426. return common.Hash{}, err
  427. }
  428. pmt, err := createPrivacyMarkerTransaction(s.b, signed, &args.PrivateTxArgs)
  429. if err != nil {
  430. log.Warn("Failed to create privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  431. return common.Hash{}, err
  432. }
  433. var pmtChainID *big.Int // PMT is public so will have different chainID used in signing compared to the internal tx
  434. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  435. pmtChainID = config.ChainID
  436. }
  437. signed, err = wallet.SignTxWithPassphrase(account, passwd, pmt, pmtChainID)
  438. if err != nil {
  439. log.Warn("Failed to sign privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  440. return common.Hash{}, err
  441. }
  442. }
  443. // /Quorum
  444. return SubmitTransaction(ctx, s.b, signed, args.PrivateFrom, false)
  445. }
  446. // SignTransaction will create a transaction from the given arguments and
  447. // tries to sign it with the key associated with args.From. If the given passwd isn't
  448. // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
  449. // to other nodes
  450. func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
  451. // No need to obtain the noncelock mutex, since we won't be sending this
  452. // tx into the transaction pool, but right back to the user
  453. if args.Gas == nil {
  454. return nil, fmt.Errorf("gas not specified")
  455. }
  456. if args.GasPrice == nil {
  457. return nil, fmt.Errorf("gasPrice not specified")
  458. }
  459. if args.Nonce == nil {
  460. return nil, fmt.Errorf("nonce not specified")
  461. }
  462. // Before actually sign the transaction, ensure the transaction fee is reasonable.
  463. if err := checkTxFee(args.GasPrice.ToInt(), uint64(*args.Gas), s.b.RPCTxFeeCap()); err != nil {
  464. return nil, err
  465. }
  466. signed, err := s.signTransaction(ctx, &args, passwd)
  467. if err != nil {
  468. log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  469. return nil, err
  470. }
  471. data, err := signed.MarshalBinary()
  472. if err != nil {
  473. return nil, err
  474. }
  475. return &SignTransactionResult{data, signed}, nil
  476. }
  477. // Sign calculates an Ethereum ECDSA signature for:
  478. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
  479. //
  480. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  481. // where the V value will be 27 or 28 for legacy reasons.
  482. //
  483. // The key used to calculate the signature is decrypted with the given password.
  484. //
  485. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
  486. func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
  487. // Look up the wallet containing the requested signer
  488. account := accounts.Account{Address: addr}
  489. wallet, err := s.b.AccountManager().Find(account)
  490. if err != nil {
  491. return nil, err
  492. }
  493. // Assemble sign the data with the wallet
  494. signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
  495. if err != nil {
  496. log.Warn("Failed data sign attempt", "address", addr, "err", err)
  497. return nil, err
  498. }
  499. signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  500. return signature, nil
  501. }
  502. // EcRecover returns the address for the account that was used to create the signature.
  503. // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
  504. // the address of:
  505. // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
  506. // addr = ecrecover(hash, signature)
  507. //
  508. // Note, the signature must conform to the secp256k1 curve R, S and V values, where
  509. // the V value must be 27 or 28 for legacy reasons.
  510. //
  511. // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
  512. func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
  513. if len(sig) != crypto.SignatureLength {
  514. return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
  515. }
  516. if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
  517. return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
  518. }
  519. sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
  520. rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
  521. if err != nil {
  522. return common.Address{}, err
  523. }
  524. return crypto.PubkeyToAddress(*rpk), nil
  525. }
  526. // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
  527. // and will be removed in the future. It primary goal is to give clients time to update.
  528. func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
  529. return s.SendTransaction(ctx, args, passwd)
  530. }
  531. // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
  532. func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
  533. wallet, err := s.am.Wallet(url)
  534. if err != nil {
  535. return "", err
  536. }
  537. entropy, err := bip39.NewEntropy(256)
  538. if err != nil {
  539. return "", err
  540. }
  541. mnemonic, err := bip39.NewMnemonic(entropy)
  542. if err != nil {
  543. return "", err
  544. }
  545. seed := bip39.NewSeed(mnemonic, "")
  546. switch wallet := wallet.(type) {
  547. case *scwallet.Wallet:
  548. return mnemonic, wallet.Initialize(seed)
  549. default:
  550. return "", fmt.Errorf("specified wallet does not support initialization")
  551. }
  552. }
  553. // Unpair deletes a pairing between wallet and geth.
  554. func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
  555. wallet, err := s.am.Wallet(url)
  556. if err != nil {
  557. return err
  558. }
  559. switch wallet := wallet.(type) {
  560. case *scwallet.Wallet:
  561. return wallet.Unpair([]byte(pin))
  562. default:
  563. return fmt.Errorf("specified wallet does not support pairing")
  564. }
  565. }
  566. // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
  567. // It offers only methods that operate on public data that is freely available to anyone.
  568. type PublicBlockChainAPI struct {
  569. b Backend
  570. }
  571. // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
  572. func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
  573. return &PublicBlockChainAPI{b}
  574. }
  575. // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
  576. func (api *PublicBlockChainAPI) ChainId() (*hexutil.Big, error) {
  577. // if current block is at or past the EIP-155 replay-protection fork block, return chainID from config
  578. if config := api.b.ChainConfig(); config.IsEIP155(api.b.CurrentBlock().Number()) {
  579. return (*hexutil.Big)(config.ChainID), nil
  580. }
  581. return nil, fmt.Errorf("chain not synced beyond EIP-155 replay-protection fork block")
  582. }
  583. // GetPSI - retunrs the PSI that was resolved based on the client request
  584. func (s *PublicBlockChainAPI) GetPSI(ctx context.Context) (string, error) {
  585. psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  586. if err != nil {
  587. return "", err
  588. }
  589. return psm.ID.String(), nil
  590. }
  591. // BlockNumber returns the block number of the chain head.
  592. func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
  593. header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
  594. return hexutil.Uint64(header.Number.Uint64())
  595. }
  596. // GetBalance returns the amount of wei for the given address in the state of the
  597. // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
  598. // block numbers are also allowed.
  599. func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
  600. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  601. if state == nil || err != nil {
  602. return nil, err
  603. }
  604. return (*hexutil.Big)(state.GetBalance(address)), state.Error()
  605. }
  606. // Result structs for GetProof
  607. type AccountResult struct {
  608. Address common.Address `json:"address"`
  609. AccountProof []string `json:"accountProof"`
  610. Balance *hexutil.Big `json:"balance"`
  611. CodeHash common.Hash `json:"codeHash"`
  612. Nonce hexutil.Uint64 `json:"nonce"`
  613. StorageHash common.Hash `json:"storageHash"`
  614. StorageProof []StorageResult `json:"storageProof"`
  615. }
  616. type StorageResult struct {
  617. Key string `json:"key"`
  618. Value *hexutil.Big `json:"value"`
  619. Proof []string `json:"proof"`
  620. }
  621. // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
  622. func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
  623. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  624. if state == nil || err != nil {
  625. return nil, err
  626. }
  627. storageTrie := state.StorageTrie(address)
  628. storageHash := types.EmptyRootHash
  629. codeHash := state.GetCodeHash(address)
  630. storageProof := make([]StorageResult, len(storageKeys))
  631. // if we have a storageTrie, (which means the account exists), we can update the storagehash
  632. if storageTrie != nil {
  633. storageHash = storageTrie.Hash()
  634. } else {
  635. // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
  636. codeHash = crypto.Keccak256Hash(nil)
  637. }
  638. // create the proof for the storageKeys
  639. for i, key := range storageKeys {
  640. if storageTrie != nil {
  641. proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
  642. if storageError != nil {
  643. return nil, storageError
  644. }
  645. storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)}
  646. } else {
  647. storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
  648. }
  649. }
  650. // create the accountProof
  651. accountProof, proofErr := state.GetProof(address)
  652. if proofErr != nil {
  653. return nil, proofErr
  654. }
  655. return &AccountResult{
  656. Address: address,
  657. AccountProof: toHexSlice(accountProof),
  658. Balance: (*hexutil.Big)(state.GetBalance(address)),
  659. CodeHash: codeHash,
  660. Nonce: hexutil.Uint64(state.GetNonce(address)),
  661. StorageHash: storageHash,
  662. StorageProof: storageProof,
  663. }, state.Error()
  664. }
  665. // GetHeaderByNumber returns the requested canonical block header.
  666. // * When blockNr is -1 the chain head is returned.
  667. // * When blockNr is -2 the pending chain head is returned.
  668. func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
  669. header, err := s.b.HeaderByNumber(ctx, number)
  670. if header != nil && err == nil {
  671. response := s.rpcMarshalHeader(ctx, header)
  672. if number == rpc.PendingBlockNumber {
  673. // Pending header need to nil out a few fields
  674. for _, field := range []string{"hash", "nonce", "miner"} {
  675. response[field] = nil
  676. }
  677. }
  678. return response, err
  679. }
  680. return nil, err
  681. }
  682. // GetHeaderByHash returns the requested header by hash.
  683. func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
  684. header, _ := s.b.HeaderByHash(ctx, hash)
  685. if header != nil {
  686. return s.rpcMarshalHeader(ctx, header)
  687. }
  688. return nil
  689. }
  690. // GetBlockByNumber returns the requested canonical block.
  691. // * When blockNr is -1 the chain head is returned.
  692. // * When blockNr is -2 the pending chain head is returned.
  693. // * When fullTx is true all transactions in the block are returned, otherwise
  694. // only the transaction hash is returned.
  695. func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
  696. block, err := s.b.BlockByNumber(ctx, number)
  697. if block != nil && err == nil {
  698. response, err := s.rpcMarshalBlock(ctx, block, true, fullTx)
  699. if err == nil && number == rpc.PendingBlockNumber {
  700. // Pending blocks need to nil out a few fields
  701. for _, field := range []string{"hash", "nonce", "miner"} {
  702. response[field] = nil
  703. }
  704. }
  705. return response, err
  706. }
  707. return nil, err
  708. }
  709. // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
  710. // detail, otherwise only the transaction hash is returned.
  711. func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
  712. block, err := s.b.BlockByHash(ctx, hash)
  713. if block != nil {
  714. return s.rpcMarshalBlock(ctx, block, true, fullTx)
  715. }
  716. return nil, err
  717. }
  718. // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  719. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  720. func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
  721. block, err := s.b.BlockByNumber(ctx, blockNr)
  722. if block != nil {
  723. uncles := block.Uncles()
  724. if index >= hexutil.Uint(len(uncles)) {
  725. log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
  726. return nil, nil
  727. }
  728. block = types.NewBlockWithHeader(uncles[index])
  729. return s.rpcMarshalBlock(ctx, block, false, false)
  730. }
  731. return nil, err
  732. }
  733. // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
  734. // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
  735. func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
  736. block, err := s.b.BlockByHash(ctx, blockHash)
  737. if block != nil {
  738. uncles := block.Uncles()
  739. if index >= hexutil.Uint(len(uncles)) {
  740. log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
  741. return nil, nil
  742. }
  743. block = types.NewBlockWithHeader(uncles[index])
  744. return s.rpcMarshalBlock(ctx, block, false, false)
  745. }
  746. return nil, err
  747. }
  748. // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
  749. func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  750. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  751. n := hexutil.Uint(len(block.Uncles()))
  752. return &n
  753. }
  754. return nil
  755. }
  756. // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
  757. func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  758. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  759. n := hexutil.Uint(len(block.Uncles()))
  760. return &n
  761. }
  762. return nil
  763. }
  764. // GetCode returns the code stored at the given address in the state for the given block number.
  765. func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  766. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  767. if state == nil || err != nil {
  768. return nil, err
  769. }
  770. code := state.GetCode(address)
  771. return code, state.Error()
  772. }
  773. // GetStorageAt returns the storage from the state at the given address, key and
  774. // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
  775. // numbers are also allowed.
  776. func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
  777. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  778. if state == nil || err != nil {
  779. return nil, err
  780. }
  781. res := state.GetState(address, common.HexToHash(key))
  782. return res[:], state.Error()
  783. }
  784. // CallArgs represents the arguments for a call.
  785. type CallArgs struct {
  786. From *common.Address `json:"from"`
  787. To *common.Address `json:"to"`
  788. Gas *hexutil.Uint64 `json:"gas"`
  789. GasPrice *hexutil.Big `json:"gasPrice"`
  790. Value *hexutil.Big `json:"value"`
  791. Data *hexutil.Bytes `json:"data"`
  792. AccessList *types.AccessList `json:"accessList"`
  793. }
  794. // ToMessage converts CallArgs to the Message type used by the core evm
  795. func (args *CallArgs) ToMessage(globalGasCap uint64) types.Message {
  796. // Set sender address or use zero address if none specified.
  797. var addr common.Address
  798. if args.From != nil {
  799. addr = *args.From
  800. }
  801. // Set default gas & gas price if none were set
  802. gas := globalGasCap
  803. if gas == 0 {
  804. gas = uint64(math.MaxUint64 / 2)
  805. }
  806. if args.Gas != nil {
  807. gas = uint64(*args.Gas)
  808. }
  809. if globalGasCap != 0 && globalGasCap < gas {
  810. log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
  811. gas = globalGasCap
  812. }
  813. gasPrice := new(big.Int)
  814. if args.GasPrice != nil {
  815. gasPrice = args.GasPrice.ToInt()
  816. }
  817. value := new(big.Int)
  818. if args.Value != nil {
  819. value = args.Value.ToInt()
  820. }
  821. var data []byte
  822. if args.Data != nil {
  823. data = *args.Data
  824. }
  825. var accessList types.AccessList
  826. if args.AccessList != nil {
  827. accessList = *args.AccessList
  828. }
  829. msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, accessList, false)
  830. return msg
  831. }
  832. // OverrideAccount indicates the overriding fields of account during the execution
  833. // of a message call.
  834. // Note, state and stateDiff can't be specified at the same time. If state is
  835. // set, message execution will only use the data in the given state. Otherwise
  836. // if statDiff is set, all diff will be applied first and then execute the call
  837. // message.
  838. type OverrideAccount struct {
  839. Nonce *hexutil.Uint64 `json:"nonce"`
  840. Code *hexutil.Bytes `json:"code"`
  841. Balance **hexutil.Big `json:"balance"`
  842. State *map[common.Hash]common.Hash `json:"state"`
  843. StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
  844. }
  845. // StateOverride is the collection of overridden accounts.
  846. type StateOverride map[common.Address]OverrideAccount
  847. // Apply overrides the fields of specified accounts into the given state.
  848. func (diff *StateOverride) Apply(state *state.StateDB) error {
  849. if diff == nil {
  850. return nil
  851. }
  852. for addr, account := range *diff {
  853. // Override account nonce.
  854. if account.Nonce != nil {
  855. state.SetNonce(addr, uint64(*account.Nonce))
  856. }
  857. // Override account(contract) code.
  858. if account.Code != nil {
  859. state.SetCode(addr, *account.Code)
  860. }
  861. // Override account balance.
  862. if account.Balance != nil {
  863. state.SetBalance(addr, (*big.Int)(*account.Balance))
  864. }
  865. if account.State != nil && account.StateDiff != nil {
  866. return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
  867. }
  868. // Replace entire state if caller requires.
  869. if account.State != nil {
  870. state.SetStorage(addr, *account.State)
  871. }
  872. // Apply state diff into specified accounts.
  873. if account.StateDiff != nil {
  874. for key, value := range *account.StateDiff {
  875. state.SetState(addr, key, value)
  876. }
  877. }
  878. }
  879. return nil
  880. }
  881. // Quorum - Multitenancy
  882. // Before returning the result, we need to inspect the EVM and
  883. // perform verification check
  884. func DoCall(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, vmCfg vm.Config, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
  885. defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  886. state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  887. if state == nil || err != nil {
  888. return nil, err
  889. }
  890. /*if err := overrides.Apply(state.(eth.EthAPIState)); err != nil {
  891. return nil, err
  892. }*/
  893. // Setup context so it may be cancelled the call has completed
  894. // or, in case of unmetered gas, setup a context with a timeout.
  895. var cancel context.CancelFunc
  896. if timeout > 0 {
  897. ctx, cancel = context.WithTimeout(ctx, timeout)
  898. } else {
  899. ctx, cancel = context.WithCancel(ctx)
  900. }
  901. // Make sure the context is cancelled when the call has completed
  902. // this makes sure resources are cleaned up.
  903. defer cancel()
  904. // Get a new instance of the EVM.
  905. msg := args.ToMessage(globalGasCap)
  906. evm, vmError, err := b.GetEVM(ctx, msg, state, header, nil)
  907. if err != nil {
  908. return nil, err
  909. }
  910. // Wait for the context to be done and cancel the evm. Even if the
  911. // EVM has finished, cancelling may be done (repeatedly)
  912. go func() {
  913. <-ctx.Done()
  914. evm.Cancel()
  915. }()
  916. // Execute the message.
  917. gp := new(core.GasPool).AddGas(math.MaxUint64)
  918. result, applyErr := core.ApplyMessage(evm, msg, gp)
  919. if err := vmError(); err != nil {
  920. return nil, err
  921. }
  922. // If the timer caused an abort, return an appropriate error message
  923. if evm.Cancelled() {
  924. return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  925. }
  926. if applyErr != nil {
  927. return result, fmt.Errorf("err: %w (supplied gas %d)", applyErr, msg.Gas())
  928. }
  929. return result, nil
  930. }
  931. func newRevertError(result *core.ExecutionResult) *revertError {
  932. reason, errUnpack := abi.UnpackRevert(result.Revert())
  933. err := errors.New("execution reverted")
  934. if errUnpack == nil {
  935. err = fmt.Errorf("execution reverted: %v", reason)
  936. }
  937. return &revertError{
  938. error: err,
  939. reason: hexutil.Encode(result.Revert()),
  940. }
  941. }
  942. // revertError is an API error that encompassas an EVM revertal with JSON error
  943. // code and a binary data blob.
  944. type revertError struct {
  945. error
  946. reason string // revert reason hex encoded
  947. }
  948. // ErrorCode returns the JSON error code for a revertal.
  949. // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
  950. func (e *revertError) ErrorCode() int {
  951. return 3
  952. }
  953. // ErrorData returns the hex encoded revert reason.
  954. func (e *revertError) ErrorData() interface{} {
  955. return e.reason
  956. }
  957. // Call executes the given transaction on the state for the given block number.
  958. //
  959. // Additionally, the caller can specify a batch of contract for fields overriding.
  960. //
  961. // Note, this function doesn't make and changes in the state/blockchain and is
  962. // useful to execute and retrieve values.
  963. // Quorum
  964. // - replaced the default 5s time out with the value passed in vm.calltimeout
  965. // - multi tenancy verification
  966. func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) {
  967. var accounts map[common.Address]OverrideAccount
  968. if overrides != nil {
  969. accounts = *overrides
  970. }
  971. stateOverride := StateOverride(accounts)
  972. result, err := DoCall(ctx, s.b, args, blockNrOrHash, &stateOverride, vm.Config{}, s.b.CallTimeOut(), s.b.RPCGasCap())
  973. if err != nil {
  974. return nil, err
  975. }
  976. // If the result contains a revert reason, try to unpack and return it.
  977. if len(result.Revert()) > 0 {
  978. return nil, newRevertError(result)
  979. }
  980. return result.Return(), result.Err
  981. }
  982. func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  983. // Binary search the gas requirement, as it may be higher than the amount used
  984. var (
  985. lo uint64 = params.TxGas - 1
  986. hi uint64
  987. cap uint64
  988. )
  989. // Use zero address if sender unspecified.
  990. if args.From == nil {
  991. args.From = new(common.Address)
  992. }
  993. // Determine the highest gas limit can be used during the estimation.
  994. if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  995. hi = uint64(*args.Gas)
  996. } else {
  997. // Retrieve the block to act as the gas ceiling
  998. block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  999. if err != nil {
  1000. return 0, err
  1001. }
  1002. if block == nil {
  1003. return 0, errors.New("block not found")
  1004. }
  1005. hi = block.GasLimit()
  1006. }
  1007. // Recap the highest gas limit with account's available balance.
  1008. if args.GasPrice != nil && args.GasPrice.ToInt().BitLen() != 0 {
  1009. state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1010. if err != nil {
  1011. return 0, err
  1012. }
  1013. balance := state.GetBalance(*args.From) // from can't be nil
  1014. available := new(big.Int).Set(balance)
  1015. if args.Value != nil {
  1016. if args.Value.ToInt().Cmp(available) >= 0 {
  1017. return 0, errors.New("insufficient funds for transfer")
  1018. }
  1019. available.Sub(available, args.Value.ToInt())
  1020. }
  1021. allowance := new(big.Int).Div(available, args.GasPrice.ToInt())
  1022. // If the allowance is larger than maximum uint64, skip checking
  1023. if allowance.IsUint64() && hi > allowance.Uint64() {
  1024. transfer := args.Value
  1025. if transfer == nil {
  1026. transfer = new(hexutil.Big)
  1027. }
  1028. log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  1029. "sent", transfer.ToInt(), "gasprice", args.GasPrice.ToInt(), "fundable", allowance)
  1030. hi = allowance.Uint64()
  1031. }
  1032. }
  1033. // Recap the highest gas allowance with specified gascap.
  1034. if gasCap != 0 && hi > gasCap {
  1035. log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  1036. hi = gasCap
  1037. }
  1038. cap = hi
  1039. // Create a helper to check if a gas allowance results in an executable transaction
  1040. executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  1041. args.Gas = (*hexutil.Uint64)(&gas)
  1042. result, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
  1043. if err != nil {
  1044. if errors.Is(err, core.ErrIntrinsicGas) {
  1045. return true, nil, nil // Special case, raise gas limit
  1046. }
  1047. return true, nil, err // Bail out
  1048. }
  1049. return result.Failed(), result, nil
  1050. }
  1051. // Execute the binary search and hone in on an executable gas limit
  1052. for lo+1 < hi {
  1053. mid := (hi + lo) / 2
  1054. failed, _, err := executable(mid)
  1055. // If the error is not nil(consensus error), it means the provided message
  1056. // call or transaction will never be accepted no matter how much gas it is
  1057. // assigned. Return the error directly, don't struggle any more.
  1058. if err != nil {
  1059. return 0, err
  1060. }
  1061. if failed {
  1062. lo = mid
  1063. } else {
  1064. hi = mid
  1065. }
  1066. }
  1067. // Reject the transaction as invalid if it still fails at the highest allowance
  1068. if hi == cap {
  1069. failed, result, err := executable(hi)
  1070. if err != nil {
  1071. return 0, err
  1072. }
  1073. if failed {
  1074. if result != nil && result.Err != vm.ErrOutOfGas {
  1075. if len(result.Revert()) > 0 {
  1076. return 0, newRevertError(result)
  1077. }
  1078. return 0, result.Err
  1079. }
  1080. // Otherwise, the specified gas cap is too low
  1081. return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  1082. }
  1083. }
  1084. //QUORUM
  1085. //We don't know if this is going to be a private or public transaction
  1086. //It is possible to have a data field that has a lower intrinsic value than the PTM hash
  1087. //so this checks that if we were to place a PTM hash (with all non-zero values) here then the transaction would
  1088. //still run
  1089. //This makes the return value a potential over-estimate of gas, rather than the exact cost to run right now
  1090. //if the transaction has a value then it cannot be private, so we can skip this check
  1091. if args.Value != nil && args.Value.ToInt().Cmp(big.NewInt(0)) == 0 {
  1092. currentBlockHeight := b.CurrentHeader().Number
  1093. homestead := b.ChainConfig().IsHomestead(currentBlockHeight)
  1094. istanbul := b.ChainConfig().IsIstanbul(currentBlockHeight)
  1095. var data []byte
  1096. if args.Data == nil {
  1097. data = nil
  1098. } else {
  1099. data = []byte(*args.Data)
  1100. }
  1101. var accessList types.AccessList
  1102. if args.AccessList != nil {
  1103. accessList = *args.AccessList
  1104. }
  1105. intrinsicGasPublic, err := core.IntrinsicGas(data, accessList, args.To == nil, homestead, istanbul)
  1106. if err != nil {
  1107. return 0, err
  1108. }
  1109. intrinsicGasPrivate, err := core.IntrinsicGas(common.Hex2Bytes(common.MaxPrivateIntrinsicDataHex), accessList, args.To == nil, homestead, istanbul)
  1110. if err != nil {
  1111. return 0, err
  1112. }
  1113. if intrinsicGasPrivate > intrinsicGasPublic {
  1114. if math.MaxUint64-hi < intrinsicGasPrivate-intrinsicGasPublic {
  1115. return 0, fmt.Errorf("private intrinsic gas addition exceeds allowance")
  1116. }
  1117. return hexutil.Uint64(hi + (intrinsicGasPrivate - intrinsicGasPublic)), nil
  1118. }
  1119. }
  1120. //END QUORUM
  1121. return hexutil.Uint64(hi), nil
  1122. }
  1123. // EstimateGas returns an estimate of the amount of gas needed to execute the
  1124. // given transaction against the current pending block.
  1125. func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
  1126. bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1127. if blockNrOrHash != nil {
  1128. bNrOrHash = *blockNrOrHash
  1129. }
  1130. return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap())
  1131. }
  1132. // ExecutionResult groups all structured logs emitted by the EVM
  1133. // while replaying a transaction in debug mode as well as transaction
  1134. // execution status, the amount of gas used and the return value
  1135. type ExecutionResult struct {
  1136. Gas uint64 `json:"gas"`
  1137. Failed bool `json:"failed"`
  1138. ReturnValue string `json:"returnValue"`
  1139. StructLogs []StructLogRes `json:"structLogs"`
  1140. }
  1141. // StructLogRes stores a structured log emitted by the EVM while replaying a
  1142. // transaction in debug mode
  1143. type StructLogRes struct {
  1144. Pc uint64 `json:"pc"`
  1145. Op string `json:"op"`
  1146. Gas uint64 `json:"gas"`
  1147. GasCost uint64 `json:"gasCost"`
  1148. Depth int `json:"depth"`
  1149. Error error `json:"error,omitempty"`
  1150. Stack *[]string `json:"stack,omitempty"`
  1151. Memory *[]string `json:"memory,omitempty"`
  1152. Storage *map[string]string `json:"storage,omitempty"`
  1153. }
  1154. // FormatLogs formats EVM returned structured logs for json output
  1155. func FormatLogs(logs []vm.StructLog) []StructLogRes {
  1156. formatted := make([]StructLogRes, len(logs))
  1157. for index, trace := range logs {
  1158. formatted[index] = StructLogRes{
  1159. Pc: trace.Pc,
  1160. Op: trace.Op.String(),
  1161. Gas: trace.Gas,
  1162. GasCost: trace.GasCost,
  1163. Depth: trace.Depth,
  1164. Error: trace.Err,
  1165. }
  1166. if trace.Stack != nil {
  1167. stack := make([]string, len(trace.Stack))
  1168. for i, stackValue := range trace.Stack {
  1169. stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  1170. }
  1171. formatted[index].Stack = &stack
  1172. }
  1173. if trace.Memory != nil {
  1174. memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1175. for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1176. memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1177. }
  1178. formatted[index].Memory = &memory
  1179. }
  1180. if trace.Storage != nil {
  1181. storage := make(map[string]string)
  1182. for i, storageValue := range trace.Storage {
  1183. storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1184. }
  1185. formatted[index].Storage = &storage
  1186. }
  1187. }
  1188. return formatted
  1189. }
  1190. // RPCMarshalHeader converts the given header to the RPC output .
  1191. func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1192. return map[string]interface{}{
  1193. "number": (*hexutil.Big)(head.Number),
  1194. "hash": head.Hash(),
  1195. "parentHash": head.ParentHash,
  1196. "nonce": head.Nonce,
  1197. "mixHash": head.MixDigest,
  1198. "sha3Uncles": head.UncleHash,
  1199. "logsBloom": head.Bloom,
  1200. "stateRoot": head.Root,
  1201. "miner": head.Coinbase,
  1202. "difficulty": (*hexutil.Big)(head.Difficulty),
  1203. "extraData": hexutil.Bytes(head.Extra),
  1204. "size": hexutil.Uint64(head.Size()),
  1205. "gasLimit": hexutil.Uint64(head.GasLimit),
  1206. "gasUsed": hexutil.Uint64(head.GasUsed),
  1207. "timestamp": hexutil.Uint64(head.Time),
  1208. "transactionsRoot": head.TxHash,
  1209. "receiptsRoot": head.ReceiptHash,
  1210. }
  1211. }
  1212. // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1213. // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1214. // transaction hashes.
  1215. func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1216. fields := RPCMarshalHeader(block.Header())
  1217. fields["size"] = hexutil.Uint64(block.Size())
  1218. if inclTx {
  1219. formatTx := func(tx *types.Transaction) (interface{}, error) {
  1220. return tx.Hash(), nil
  1221. }
  1222. if fullTx {
  1223. formatTx = func(tx *types.Transaction) (interface{}, error) {
  1224. return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1225. }
  1226. }
  1227. txs := block.Transactions()
  1228. transactions := make([]interface{}, len(txs))
  1229. var err error
  1230. for i, tx := range txs {
  1231. if transactions[i], err = formatTx(tx); err != nil {
  1232. return nil, err
  1233. }
  1234. }
  1235. fields["transactions"] = transactions
  1236. }
  1237. uncles := block.Uncles()
  1238. uncleHashes := make([]common.Hash, len(uncles))
  1239. for i, uncle := range uncles {
  1240. uncleHashes[i] = uncle.Hash()
  1241. }
  1242. fields["uncles"] = uncleHashes
  1243. return fields, nil
  1244. }
  1245. // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1246. // a `PublicBlockchainAPI`.
  1247. func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
  1248. fields := RPCMarshalHeader(header)
  1249. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
  1250. return fields
  1251. }
  1252. // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1253. // a `PublicBlockchainAPI`.
  1254. func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1255. fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1256. if err != nil {
  1257. return nil, err
  1258. }
  1259. if inclTx {
  1260. fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash()))
  1261. }
  1262. return fields, err
  1263. }
  1264. // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1265. type RPCTransaction struct {
  1266. BlockHash *common.Hash `json:"blockHash"`
  1267. BlockNumber *hexutil.Big `json:"blockNumber"`
  1268. From common.Address `json:"from"`
  1269. Gas hexutil.Uint64 `json:"gas"`
  1270. GasPrice *hexutil.Big `json:"gasPrice"`
  1271. Hash common.Hash `json:"hash"`
  1272. Input hexutil.Bytes `json:"input"`
  1273. Nonce hexutil.Uint64 `json:"nonce"`
  1274. To *common.Address `json:"to"`
  1275. TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1276. Value *hexutil.Big `json:"value"`
  1277. Type hexutil.Uint64 `json:"type"`
  1278. Accesses *types.AccessList `json:"accessList,omitempty"`
  1279. ChainID *hexutil.Big `json:"chainId,omitempty"`
  1280. V *hexutil.Big `json:"v"`
  1281. R *hexutil.Big `json:"r"`
  1282. S *hexutil.Big `json:"s"`
  1283. }
  1284. // newRPCTransaction returns a transaction that will serialize to the RPC
  1285. // representation, with the given location metadata set (if available).
  1286. func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1287. // Determine the signer. For replay-protected transactions, use the most permissive
  1288. // signer, because we assume that signers are backwards-compatible with old
  1289. // transactions. For non-protected transactions, the homestead signer signer is used
  1290. // because the return value of ChainId is zero for those transactions.
  1291. var signer types.Signer
  1292. if tx.Protected() && !tx.IsPrivate() {
  1293. signer = types.LatestSignerForChainID(tx.ChainId())
  1294. } else {
  1295. signer = types.HomesteadSigner{}
  1296. }
  1297. from, _ := types.Sender(signer, tx)
  1298. v, r, s := tx.RawSignatureValues()
  1299. result := &RPCTransaction{
  1300. Type: hexutil.Uint64(tx.Type()),
  1301. From: from,
  1302. Gas: hexutil.Uint64(tx.Gas()),
  1303. GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1304. Hash: tx.Hash(),
  1305. Input: hexutil.Bytes(tx.Data()),
  1306. Nonce: hexutil.Uint64(tx.Nonce()),
  1307. To: tx.To(),
  1308. Value: (*hexutil.Big)(tx.Value()),
  1309. V: (*hexutil.Big)(v),
  1310. R: (*hexutil.Big)(r),
  1311. S: (*hexutil.Big)(s),
  1312. }
  1313. if blockHash != (common.Hash{}) {
  1314. result.BlockHash = &blockHash
  1315. result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1316. result.TransactionIndex = (*hexutil.Uint64)(&index)
  1317. }
  1318. if tx.Type() == types.AccessListTxType {
  1319. al := tx.AccessList()
  1320. result.Accesses = &al
  1321. result.ChainID = (*hexutil.Big)(tx.ChainId())
  1322. }
  1323. return result
  1324. }
  1325. // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1326. func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1327. return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1328. }
  1329. // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1330. func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1331. txs := b.Transactions()
  1332. if index >= uint64(len(txs)) {
  1333. return nil
  1334. }
  1335. return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1336. }
  1337. // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1338. func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1339. txs := b.Transactions()
  1340. if index >= uint64(len(txs)) {
  1341. return nil
  1342. }
  1343. blob, _ := txs[index].MarshalBinary()
  1344. return blob
  1345. }
  1346. // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1347. func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1348. for idx, tx := range b.Transactions() {
  1349. if tx.Hash() == hash {
  1350. return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1351. }
  1352. }
  1353. return nil
  1354. }
  1355. // accessListResult returns an optional accesslist
  1356. // Its the result of the `debug_createAccessList` RPC call.
  1357. // It contains an error if the transaction itself failed.
  1358. type accessListResult struct {
  1359. Accesslist *types.AccessList `json:"accessList"`
  1360. Error string `json:"error,omitempty"`
  1361. GasUsed hexutil.Uint64 `json:"gasUsed"`
  1362. }
  1363. // CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
  1364. // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
  1365. func (s *PublicBlockChainAPI) CreateAccessList(ctx context.Context, args SendTxArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
  1366. bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1367. if blockNrOrHash != nil {
  1368. bNrOrHash = *blockNrOrHash
  1369. }
  1370. acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args)
  1371. if err != nil {
  1372. return nil, err
  1373. }
  1374. result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)}
  1375. if vmerr != nil {
  1376. result.Error = vmerr.Error()
  1377. }
  1378. return result, nil
  1379. }
  1380. // AccessList creates an access list for the given transaction.
  1381. // If the accesslist creation fails an error is returned.
  1382. // If the transaction itself fails, an vmErr is returned.
  1383. func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args SendTxArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) {
  1384. // Retrieve the execution context
  1385. db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1386. if db == nil || err != nil {
  1387. return nil, 0, nil, err
  1388. }
  1389. // If the gas amount is not set, extract this as it will depend on access
  1390. // lists and we'll need to reestimate every time
  1391. nogas := args.Gas == nil
  1392. // Ensure any missing fields are filled, extract the recipient and input data
  1393. if err := args.setDefaults(ctx, b); err != nil {
  1394. return nil, 0, nil, err
  1395. }
  1396. var to common.Address
  1397. if args.To != nil {
  1398. to = *args.To
  1399. } else {
  1400. to = crypto.CreateAddress(args.From, uint64(*args.Nonce))
  1401. }
  1402. var input []byte
  1403. if args.Input != nil {
  1404. input = *args.Input
  1405. } else if args.Data != nil {
  1406. input = *args.Data
  1407. }
  1408. // Retrieve the precompiles since they don't need to be added to the access list
  1409. precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number))
  1410. // Create an initial tracer
  1411. prevTracer := vm.NewAccessListTracer(nil, args.From, to, precompiles)
  1412. if args.AccessList != nil {
  1413. prevTracer = vm.NewAccessListTracer(*args.AccessList, args.From, to, precompiles)
  1414. }
  1415. for {
  1416. // Retrieve the current access list to expand
  1417. accessList := prevTracer.AccessList()
  1418. log.Trace("Creating access list", "input", accessList)
  1419. // If no gas amount was specified, each unique access list needs it's own
  1420. // gas calculation. This is quite expensive, but we need to be accurate
  1421. // and it's convered by the sender only anyway.
  1422. if nogas {
  1423. args.Gas = nil
  1424. if err := args.setDefaults(ctx, b); err != nil {
  1425. return nil, 0, nil, err // shouldn't happen, just in case
  1426. }
  1427. }
  1428. // Copy the original db so we don't modify it
  1429. // statedb := db.Copy()
  1430. statedb := db.(*state.StateDB).Copy()
  1431. msg := types.NewMessage(args.From, args.To, uint64(*args.Nonce), args.Value.ToInt(), uint64(*args.Gas), args.GasPrice.ToInt(), input, accessList, false)
  1432. // Apply the transaction with the access list tracer
  1433. tracer := vm.NewAccessListTracer(accessList, args.From, to, precompiles)
  1434. config := vm.Config{Tracer: tracer, Debug: true}
  1435. vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config)
  1436. if err != nil {
  1437. return nil, 0, nil, err
  1438. }
  1439. res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  1440. if err != nil {
  1441. return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
  1442. }
  1443. if tracer.Equal(prevTracer) {
  1444. return accessList, res.UsedGas, res.Err, nil
  1445. }
  1446. prevTracer = tracer
  1447. }
  1448. }
  1449. // PublicTransactionPoolAPI exposes methods for the RPC interface
  1450. type PublicTransactionPoolAPI struct {
  1451. b Backend
  1452. nonceLock *AddrLocker
  1453. signer types.Signer
  1454. }
  1455. // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1456. func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1457. // The signer used by the API should always be the 'latest' known one because we expect
  1458. // signers to be backwards-compatible with old transactions.
  1459. signer := types.LatestSigner(b.ChainConfig())
  1460. return &PublicTransactionPoolAPI{b, nonceLock, signer}
  1461. }
  1462. // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1463. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1464. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1465. n := hexutil.Uint(len(block.Transactions()))
  1466. return &n
  1467. }
  1468. return nil
  1469. }
  1470. // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1471. func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1472. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1473. n := hexutil.Uint(len(block.Transactions()))
  1474. return &n
  1475. }
  1476. return nil
  1477. }
  1478. // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1479. func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1480. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1481. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1482. }
  1483. return nil
  1484. }
  1485. // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1486. func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1487. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1488. return newRPCTransactionFromBlockIndex(block, uint64(index))
  1489. }
  1490. return nil
  1491. }
  1492. // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1493. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1494. if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1495. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1496. }
  1497. return nil
  1498. }
  1499. // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1500. func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1501. if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1502. return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1503. }
  1504. return nil
  1505. }
  1506. // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1507. func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1508. // Ask transaction pool for the nonce which includes pending transactions
  1509. if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1510. nonce, err := s.b.GetPoolNonce(ctx, address)
  1511. if err != nil {
  1512. return nil, err
  1513. }
  1514. return (*hexutil.Uint64)(&nonce), nil
  1515. }
  1516. // Resolve block number and use its state to ask for the nonce
  1517. state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1518. if state == nil || err != nil {
  1519. return nil, err
  1520. }
  1521. nonce := state.GetNonce(address)
  1522. return (*hexutil.Uint64)(&nonce), state.Error()
  1523. }
  1524. // Quorum
  1525. type PrivacyMetadataWithMandatoryRecipients struct {
  1526. *state.PrivacyMetadata
  1527. MandatoryRecipients []string `json:"mandatoryFor,omitempty"`
  1528. }
  1529. func (s *PublicTransactionPoolAPI) GetContractPrivacyMetadata(ctx context.Context, address common.Address) (*PrivacyMetadataWithMandatoryRecipients, error) {
  1530. state, _, err := s.b.StateAndHeaderByNumber(ctx, rpc.LatestBlockNumber)
  1531. if state == nil || err != nil {
  1532. return nil, err
  1533. }
  1534. var mandatoryRecipients []string
  1535. privacyMetadata, err := state.GetPrivacyMetadata(address)
  1536. if privacyMetadata == nil || err != nil {
  1537. return nil, err
  1538. }
  1539. if privacyMetadata.PrivacyFlag == engine.PrivacyFlagMandatoryRecipients {
  1540. mandatoryRecipients, err = private.P.GetMandatory(privacyMetadata.CreationTxHash)
  1541. if len(mandatoryRecipients) == 0 || err != nil {
  1542. return nil, err
  1543. }
  1544. }
  1545. return &PrivacyMetadataWithMandatoryRecipients{privacyMetadata, mandatoryRecipients}, nil
  1546. }
  1547. // End Quorum
  1548. // GetTransactionByHash returns the transaction for the given hash
  1549. func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1550. // Try to return an already finalized transaction
  1551. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1552. if err != nil {
  1553. return nil, err
  1554. }
  1555. if tx != nil {
  1556. return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1557. }
  1558. // No finalized transaction, try to retrieve it from the pool
  1559. if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1560. return newRPCPendingTransaction(tx), nil
  1561. }
  1562. // Transaction unknown, return as such
  1563. return nil, nil
  1564. }
  1565. // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1566. func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1567. // Retrieve a finalized transaction, or a pooled otherwise
  1568. tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1569. if err != nil {
  1570. return nil, err
  1571. }
  1572. if tx == nil {
  1573. if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1574. // Transaction not found anywhere, abort
  1575. return nil, nil
  1576. }
  1577. }
  1578. // Serialize to RLP and return
  1579. return tx.MarshalBinary()
  1580. }
  1581. // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1582. func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1583. tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1584. if err != nil {
  1585. return nil, nil
  1586. }
  1587. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1588. if err != nil {
  1589. return nil, err
  1590. }
  1591. if len(receipts) <= int(index) {
  1592. return nil, nil
  1593. }
  1594. receipt := receipts[index]
  1595. // Quorum: note that upstream code has been refactored into this method
  1596. return getTransactionReceiptCommonCode(tx, blockHash, blockNumber, hash, index, receipt)
  1597. }
  1598. // Quorum
  1599. // Common code extracted from GetTransactionReceipt() to enable reuse
  1600. func getTransactionReceiptCommonCode(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, hash common.Hash, index uint64, receipt *types.Receipt) (map[string]interface{}, error) {
  1601. fields := map[string]interface{}{
  1602. "blockHash": blockHash,
  1603. "blockNumber": hexutil.Uint64(blockNumber),
  1604. "transactionHash": hash,
  1605. "transactionIndex": hexutil.Uint64(index),
  1606. "from": tx.From(),
  1607. "to": tx.To(),
  1608. "gasUsed": hexutil.Uint64(receipt.GasUsed),
  1609. "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1610. "contractAddress": nil,
  1611. "logs": receipt.Logs,
  1612. "logsBloom": receipt.Bloom,
  1613. "type": hexutil.Uint(tx.Type()),
  1614. // Quorum
  1615. "isPrivacyMarkerTransaction": tx.IsPrivacyMarker(),
  1616. }
  1617. // Quorum
  1618. if len(receipt.RevertReason) > 0 {
  1619. fields["revertReason"] = hexutil.Encode(receipt.RevertReason)
  1620. }
  1621. // End Quorum
  1622. // Assign receipt status or post state.
  1623. if len(receipt.PostState) > 0 {
  1624. fields["root"] = hexutil.Bytes(receipt.PostState)
  1625. } else {
  1626. fields["status"] = hexutil.Uint(receipt.Status)
  1627. }
  1628. if receipt.Logs == nil {
  1629. fields["logs"] = [][]*types.Log{}
  1630. }
  1631. // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1632. if receipt.ContractAddress != (common.Address{}) {
  1633. fields["contractAddress"] = receipt.ContractAddress
  1634. }
  1635. return fields, nil
  1636. }
  1637. // Quorum
  1638. // GetPrivateTransactionByHash accepts the hash for a privacy marker transaction,
  1639. // but returns the associated private transaction
  1640. func (s *PublicTransactionPoolAPI) GetPrivateTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1641. if !private.IsQuorumPrivacyEnabled() {
  1642. return nil, fmt.Errorf("PrivateTransactionManager is not enabled")
  1643. }
  1644. psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  1645. if err != nil {
  1646. return nil, err
  1647. }
  1648. // first need the privacy marker transaction
  1649. pmt, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1650. if err != nil {
  1651. return nil, err
  1652. }
  1653. // now retrieve the private transaction
  1654. if pmt != nil {
  1655. tx, managedParties, _, err := private.FetchPrivateTransaction(pmt.Data())
  1656. if err != nil {
  1657. return nil, err
  1658. }
  1659. if tx != nil && !s.b.PSMR().NotIncludeAny(psm, managedParties...) {
  1660. return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1661. }
  1662. }
  1663. // Transaction unknown or not a participant in the private transaction, return as such
  1664. return nil, nil
  1665. }
  1666. // Quorum
  1667. // GetPrivateTransactionReceipt accepts the hash for a privacy marker transaction,
  1668. // but returns the receipt of the associated private transaction
  1669. func (s *PublicTransactionPoolAPI) GetPrivateTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1670. // first need the privacy marker transaction
  1671. pmt, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1672. if err != nil {
  1673. return nil, err
  1674. }
  1675. if pmt == nil {
  1676. // Transaction unknown, return as such
  1677. return nil, errors.New("privacy marker transaction not found")
  1678. }
  1679. // now retrieve the private transaction
  1680. tx, _, _, err := private.FetchPrivateTransaction(pmt.Data())
  1681. if err != nil {
  1682. return nil, err
  1683. }
  1684. // Transaction not found, or not a participant in the private transaction, return as such
  1685. if tx == nil {
  1686. return nil, errors.New("private transaction not found for this participant")
  1687. }
  1688. // get receipt for the privacy marker transaction
  1689. receipts, err := s.b.GetReceipts(ctx, blockHash)
  1690. if err != nil {
  1691. return nil, err
  1692. }
  1693. if len(receipts) <= int(index) {
  1694. return nil, errors.New("could not find receipt for private transaction")
  1695. }
  1696. pmtReceipt := receipts[index]
  1697. // now extract the receipt for the private transaction
  1698. psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  1699. if err != nil {
  1700. return nil, err
  1701. }
  1702. receipt := pmtReceipt.PSReceipts[psm.ID]
  1703. if receipt == nil {
  1704. return nil, errors.New("could not find receipt for private transaction")
  1705. }
  1706. return getTransactionReceiptCommonCode(tx, blockHash, blockNumber, hash, index, receipt)
  1707. }
  1708. // Quorum: if signing a private TX, set with tx.SetPrivate() before calling this method.
  1709. // sign is a helper function that signs a transaction with the private key of the given address.
  1710. func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1711. // Look up the wallet containing the requested signer
  1712. account := accounts.Account{Address: addr}
  1713. wallet, err := s.b.AccountManager().Find(account)
  1714. if err != nil {
  1715. return nil, err
  1716. }
  1717. // Quorum
  1718. var chainID *big.Int
  1719. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  1720. chainID = config.ChainID
  1721. }
  1722. // /Quorum
  1723. // Request the wallet to sign the transaction
  1724. return wallet.SignTx(account, tx, chainID)
  1725. }
  1726. // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1727. // Quorum: introducing additional arguments encapsulated in PrivateTxArgs struct
  1728. // to support private transactions processing.
  1729. type SendTxArgs struct {
  1730. PrivateTxArgs // Quorum
  1731. From common.Address `json:"from"`
  1732. To *common.Address `json:"to"`
  1733. Gas *hexutil.Uint64 `json:"gas"`
  1734. GasPrice *hexutil.Big `json:"gasPrice"`
  1735. Value *hexutil.Big `json:"value"`
  1736. Nonce *hexutil.Uint64 `json:"nonce"`
  1737. // We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1738. // newer name and should be preferred by clients.
  1739. Data *hexutil.Bytes `json:"data"`
  1740. Input *hexutil.Bytes `json:"input"`
  1741. // For non-legacy transactions
  1742. AccessList *types.AccessList `json:"accessList,omitempty"`
  1743. ChainID *hexutil.Big `json:"chainId,omitempty"`
  1744. }
  1745. func (s SendTxArgs) IsPrivate() bool {
  1746. return s.PrivateFor != nil
  1747. }
  1748. // SendRawTxArgs represents the arguments to submit a new signed private transaction into the transaction pool.
  1749. type SendRawTxArgs struct {
  1750. PrivateTxArgs
  1751. }
  1752. // Additional arguments used in private transactions
  1753. type PrivateTxArgs struct {
  1754. // PrivateFrom is the public key of the sending party.
  1755. // The public key must be available in the Private Transaction Manager (i.e.: Tessera) which is paired with this geth node.
  1756. // Empty value means the Private Transaction Manager will use the first public key
  1757. // in its list of available keys which it maintains.
  1758. PrivateFrom string `json:"privateFrom"`
  1759. // PrivateFor is the list of public keys which are available in the Private Transaction Managers in the network.
  1760. // The transaction payload is only visible to those party to the transaction.
  1761. PrivateFor []string `json:"privateFor"`
  1762. PrivateTxType string `json:"restriction"`
  1763. PrivacyFlag engine.PrivacyFlagType `json:"privacyFlag"`
  1764. MandatoryRecipients []string `json:"mandatoryFor"`
  1765. }
  1766. func (args *PrivateTxArgs) SetDefaultPrivateFrom(ctx context.Context, b Backend) error {
  1767. if args.PrivateFor != nil && len(args.PrivateFrom) == 0 && b.ChainConfig().IsMPS {
  1768. psm, err := b.PSMR().ResolveForUserContext(ctx)
  1769. if err != nil {
  1770. return err
  1771. }
  1772. args.PrivateFrom = psm.Addresses[0]
  1773. }
  1774. return nil
  1775. }
  1776. func (args *PrivateTxArgs) SetRawTransactionPrivateFrom(ctx context.Context, b Backend, tx *types.Transaction) error {
  1777. if args.PrivateFor != nil && b.ChainConfig().IsMPS {
  1778. hash := common.BytesToEncryptedPayloadHash(tx.Data())
  1779. _, retrievedPrivateFrom, _, err := private.P.ReceiveRaw(hash)
  1780. if err != nil {
  1781. return err
  1782. }
  1783. if len(args.PrivateFrom) == 0 {
  1784. args.PrivateFrom = retrievedPrivateFrom
  1785. }
  1786. if args.PrivateFrom != retrievedPrivateFrom {
  1787. return fmt.Errorf("The PrivateFrom address retrieved from the privacy manager does not match private PrivateFrom (%s) specified in transaction arguments.", args.PrivateFrom)
  1788. }
  1789. psm, err := b.PSMR().ResolveForUserContext(ctx)
  1790. if err != nil {
  1791. return err
  1792. }
  1793. if psm.NotIncludeAny(args.PrivateFrom) {
  1794. return fmt.Errorf("The PrivateFrom address does not match the specified private state (%s)", psm.ID)
  1795. }
  1796. }
  1797. return nil
  1798. }
  1799. // setDefaults fills in default values for unspecified tx fields.
  1800. func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1801. if args.GasPrice == nil {
  1802. price, err := b.SuggestPrice(ctx)
  1803. if err != nil {
  1804. return err
  1805. }
  1806. args.GasPrice = (*hexutil.Big)(price)
  1807. }
  1808. if args.Value == nil {
  1809. args.Value = new(hexutil.Big)
  1810. }
  1811. if args.Nonce == nil {
  1812. nonce, err := b.GetPoolNonce(ctx, args.From)
  1813. if err != nil {
  1814. return err
  1815. }
  1816. args.Nonce = (*hexutil.Uint64)(&nonce)
  1817. }
  1818. if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1819. return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
  1820. }
  1821. if args.To == nil {
  1822. // Contract creation
  1823. var input []byte
  1824. if args.Data != nil {
  1825. input = *args.Data
  1826. } else if args.Input != nil {
  1827. input = *args.Input
  1828. }
  1829. if len(input) == 0 {
  1830. return errors.New(`contract creation without any data provided`)
  1831. }
  1832. }
  1833. // Estimate the gas usage if necessary.
  1834. if args.Gas == nil {
  1835. // For backwards-compatibility reason, we try both input and data
  1836. // but input is preferred.
  1837. input := args.Input
  1838. if input == nil {
  1839. input = args.Data
  1840. }
  1841. callArgs := CallArgs{
  1842. From: &args.From, // From shouldn't be nil
  1843. To: args.To,
  1844. GasPrice: args.GasPrice,
  1845. Value: args.Value,
  1846. Data: input,
  1847. AccessList: args.AccessList,
  1848. }
  1849. pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1850. estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1851. if err != nil {
  1852. return err
  1853. }
  1854. args.Gas = &estimated
  1855. log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1856. }
  1857. if args.ChainID == nil {
  1858. id := (*hexutil.Big)(b.ChainConfig().ChainID)
  1859. args.ChainID = id
  1860. }
  1861. // Quorum
  1862. if args.PrivateTxType == "" {
  1863. args.PrivateTxType = "restricted"
  1864. }
  1865. return args.SetDefaultPrivateFrom(ctx, b)
  1866. // End Quorum
  1867. }
  1868. // toTransaction converts the arguments to a transaction.
  1869. // This assumes that setDefaults has been called.
  1870. func (args *SendTxArgs) toTransaction() *types.Transaction {
  1871. var input []byte
  1872. if args.Input != nil {
  1873. input = *args.Input
  1874. } else if args.Data != nil {
  1875. input = *args.Data
  1876. }
  1877. var data types.TxData
  1878. if args.AccessList == nil {
  1879. data = &types.LegacyTx{
  1880. To: args.To,
  1881. Nonce: uint64(*args.Nonce),
  1882. Gas: uint64(*args.Gas),
  1883. GasPrice: (*big.Int)(args.GasPrice),
  1884. Value: (*big.Int)(args.Value),
  1885. Data: input,
  1886. }
  1887. } else {
  1888. data = &types.AccessListTx{
  1889. To: args.To,
  1890. ChainID: (*big.Int)(args.ChainID),
  1891. Nonce: uint64(*args.Nonce),
  1892. Gas: uint64(*args.Gas),
  1893. GasPrice: (*big.Int)(args.GasPrice),
  1894. Value: (*big.Int)(args.Value),
  1895. Data: input,
  1896. AccessList: *args.AccessList,
  1897. }
  1898. }
  1899. return types.NewTx(data)
  1900. }
  1901. // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1902. func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateFrom string, isRaw bool) (common.Hash, error) {
  1903. // If the transaction fee cap is already specified, ensure the
  1904. // fee of the given transaction is _reasonable_.
  1905. if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1906. return common.Hash{}, err
  1907. }
  1908. if !b.UnprotectedAllowed() && !tx.Protected() {
  1909. // Ensure only eip155 signed transactions are submitted if EIP155Required is set.
  1910. return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC")
  1911. }
  1912. // Print a log with full tx details for manual investigations and interventions
  1913. // Quorum
  1914. var signer types.Signer
  1915. if tx.IsPrivate() {
  1916. signer = types.QuorumPrivateTxSigner{}
  1917. } else {
  1918. signer = types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1919. }
  1920. from, err := types.Sender(signer, tx)
  1921. if err != nil {
  1922. return common.Hash{}, err
  1923. }
  1924. // Quorum
  1925. // Need to do authorization check for Ethereum Account being used in signing.
  1926. // We only care about private transactions (or the private transaction relating to a privacy marker)
  1927. if token, ok := b.SupportsMultitenancy(ctx); ok {
  1928. tx := tx
  1929. // If we are sending a Privacy Marker Transaction, then get the private txn details
  1930. if tx.IsPrivacyMarker() {
  1931. tx, _, _, err = private.FetchPrivateTransaction(tx.Data())
  1932. if err != nil {
  1933. return common.Hash{}, err
  1934. }
  1935. }
  1936. innerFrom, err := types.Sender(signer, tx)
  1937. if err != nil {
  1938. return common.Hash{}, err
  1939. }
  1940. if tx.IsPrivate() {
  1941. psm, err := b.PSMR().ResolveForUserContext(ctx)
  1942. if err != nil {
  1943. return common.Hash{}, err
  1944. }
  1945. eoaSecAttr := (&multitenancy.PrivateStateSecurityAttribute{}).WithPSI(psm.ID).WithSelfEOAIf(isRaw, innerFrom)
  1946. psm, err = b.PSMR().ResolveForManagedParty(privateFrom)
  1947. if err != nil {
  1948. return common.Hash{}, err
  1949. }
  1950. privateFromSecAttr := (&multitenancy.PrivateStateSecurityAttribute{}).WithPSI(psm.ID).WithSelfEOAIf(isRaw, innerFrom)
  1951. if isAuthorized, _ := multitenancy.IsAuthorized(token, eoaSecAttr, privateFromSecAttr); !isAuthorized {
  1952. return common.Hash{}, multitenancy.ErrNotAuthorized
  1953. }
  1954. }
  1955. }
  1956. if !b.UnprotectedAllowed() && !tx.Protected() {
  1957. // Ensure only eip155 signed transactions are submitted if EIP155Required is set.
  1958. return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC")
  1959. }
  1960. if err := b.SendTx(ctx, tx); err != nil {
  1961. return common.Hash{}, err
  1962. }
  1963. if tx.To() == nil {
  1964. addr := crypto.CreateAddress(from, tx.Nonce())
  1965. log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value())
  1966. log.EmitCheckpoint(log.TxCreated, "tx", tx.Hash().Hex(), "to", addr.Hex())
  1967. } else {
  1968. log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value())
  1969. log.EmitCheckpoint(log.TxCreated, "tx", tx.Hash().Hex(), "to", tx.To().Hex())
  1970. }
  1971. return tx.Hash(), nil
  1972. }
  1973. // runSimulation runs a simulation of the given transaction.
  1974. // It returns the EVM instance upon completion
  1975. func runSimulation(ctx context.Context, b Backend, from common.Address, tx *types.Transaction) (*vm.EVM, []byte, error) {
  1976. defer func(start time.Time) {
  1977. log.Debug("Simulated Execution EVM call finished", "runtime", time.Since(start))
  1978. }(time.Now())
  1979. // Set sender address or use a default if none specified
  1980. addr := from
  1981. if addr == (common.Address{}) {
  1982. if wallets := b.AccountManager().Wallets(); len(wallets) > 0 {
  1983. if accountList := wallets[0].Accounts(); len(accountList) > 0 {
  1984. addr = accountList[0].Address
  1985. }
  1986. }
  1987. }
  1988. // Create new call message
  1989. msg := types.NewMessage(addr, tx.To(), tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), tx.Data(), tx.AccessList(), false)
  1990. // Setup context with timeout as gas un-metered
  1991. var cancel context.CancelFunc
  1992. ctx, cancel = context.WithTimeout(ctx, time.Second*5)
  1993. // Make sure the context is cancelled when the call has completed
  1994. // this makes sure resources are cleaned up.
  1995. defer func() { cancel() }()
  1996. // Get a new instance of the EVM.
  1997. blockNumber := b.CurrentBlock().Number().Uint64()
  1998. stateAtBlock, header, err := b.StateAndHeaderByNumber(ctx, rpc.BlockNumber(blockNumber))
  1999. if stateAtBlock == nil || err != nil {
  2000. return nil, nil, err
  2001. }
  2002. evm, _, err := b.GetEVM(ctx, msg, stateAtBlock, header, &vm.Config{})
  2003. if err != nil {
  2004. return nil, nil, err
  2005. }
  2006. // Wait for the context to be done and cancel the evm. Even if the
  2007. // EVM has finished, cancelling may be done (repeatedly)
  2008. go func() {
  2009. <-ctx.Done()
  2010. evm.Cancel()
  2011. }()
  2012. var contractAddr common.Address
  2013. // even the creation of a contract (init code) can invoke other contracts
  2014. if tx.To() != nil {
  2015. // removed contract availability checks as they are performed in checkAndHandlePrivateTransaction
  2016. data, _, err := evm.Call(vm.AccountRef(addr), *tx.To(), tx.Data(), tx.Gas(), tx.Value())
  2017. return evm, data, err
  2018. } else {
  2019. _, contractAddr, _, err = evm.Create(vm.AccountRef(addr), tx.Data(), tx.Gas(), tx.Value())
  2020. //make sure that nonce is same in simulation as in actual block processing
  2021. //simulation blockNumber will be behind block processing blockNumber by at least 1
  2022. //only guaranteed to work for default config where EIP158=1
  2023. if evm.ChainConfig().IsEIP158(big.NewInt(evm.Context.BlockNumber.Int64() + 1)) {
  2024. evm.StateDB.SetNonce(contractAddr, 1)
  2025. }
  2026. }
  2027. return evm, nil, err
  2028. }
  2029. // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  2030. // transaction pool.
  2031. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  2032. // Look up the wallet containing the requested signer
  2033. account := accounts.Account{Address: args.From}
  2034. wallet, err := s.b.AccountManager().Find(account)
  2035. if err != nil {
  2036. return common.Hash{}, err
  2037. }
  2038. if args.Nonce == nil {
  2039. // Hold the addresse's mutex around signing to prevent concurrent assignment of
  2040. // the same nonce to multiple accounts.
  2041. s.nonceLock.LockAddr(args.From)
  2042. defer s.nonceLock.UnlockAddr(args.From)
  2043. }
  2044. // Set some sanity defaults and terminate on failure
  2045. if err := args.setDefaults(ctx, s.b); err != nil {
  2046. return common.Hash{}, err
  2047. }
  2048. _, replaceDataWithHash, data, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, NormalTransaction)
  2049. if err != nil {
  2050. return common.Hash{}, err
  2051. }
  2052. if replaceDataWithHash {
  2053. // replace the original payload with encrypted payload hash
  2054. args.Data = data.BytesTypeRef()
  2055. }
  2056. // /Quorum
  2057. // Assemble the transaction and sign with the wallet
  2058. tx := args.toTransaction()
  2059. // Quorum
  2060. if args.IsPrivate() {
  2061. tx.SetPrivate()
  2062. }
  2063. var chainID *big.Int
  2064. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  2065. chainID = config.ChainID
  2066. }
  2067. // /Quorum
  2068. signed, err := wallet.SignTx(account, tx, chainID)
  2069. if err != nil {
  2070. return common.Hash{}, err
  2071. }
  2072. // Quorum
  2073. if signed.IsPrivate() && s.b.IsPrivacyMarkerTransactionCreationEnabled() {
  2074. pmt, err := createPrivacyMarkerTransaction(s.b, signed, &args.PrivateTxArgs)
  2075. if err != nil {
  2076. log.Warn("Failed to create privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  2077. return common.Hash{}, err
  2078. }
  2079. var pmtChainID *big.Int // PMT is public so will have different chainID used in signing compared to the internal tx
  2080. if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  2081. pmtChainID = config.ChainID
  2082. }
  2083. signed, err = wallet.SignTx(account, pmt, pmtChainID)
  2084. if err != nil {
  2085. log.Warn("Failed to sign privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  2086. return common.Hash{}, err
  2087. }
  2088. }
  2089. return SubmitTransaction(ctx, s.b, signed, args.PrivateFrom, false)
  2090. }
  2091. // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  2092. // and returns it to the caller for further processing (signing + broadcast)
  2093. func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  2094. // Set some sanity defaults and terminate on failure
  2095. if err := args.setDefaults(ctx, s.b); err != nil {
  2096. return nil, err
  2097. }
  2098. // Assemble the transaction and obtain rlp
  2099. // Quorum
  2100. isPrivate, replaceDataWithHash, hash, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, FillTransaction)
  2101. if err != nil {
  2102. return nil, err
  2103. }
  2104. if replaceDataWithHash {
  2105. // replace the original payload with encrypted payload hash
  2106. args.Data = hash.BytesTypeRef()
  2107. }
  2108. // /Quorum
  2109. tx := args.toTransaction()
  2110. // Quorum
  2111. if isPrivate {
  2112. tx.SetPrivate()
  2113. }
  2114. // /Quorum
  2115. data, err := tx.MarshalBinary()
  2116. if err != nil {
  2117. return nil, err
  2118. }
  2119. return &SignTransactionResult{data, tx}, nil
  2120. }
  2121. // SendRawTransaction will add the signed transaction to the transaction pool.
  2122. // The sender is responsible for signing the transaction and using the correct nonce.
  2123. func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) {
  2124. tx := new(types.Transaction)
  2125. if err := tx.UnmarshalBinary(input); err != nil {
  2126. return common.Hash{}, err
  2127. }
  2128. return SubmitTransaction(ctx, s.b, tx, "", true)
  2129. }
  2130. // Quorum
  2131. //
  2132. // SendRawPrivateTransaction will add the signed transaction to the transaction pool.
  2133. // The sender is responsible for signing the transaction and using the correct nonce.
  2134. func (s *PublicTransactionPoolAPI) SendRawPrivateTransaction(ctx context.Context, encodedTx hexutil.Bytes, args SendRawTxArgs) (common.Hash, error) {
  2135. tx := new(types.Transaction)
  2136. if err := tx.UnmarshalBinary(encodedTx); err != nil {
  2137. return common.Hash{}, err
  2138. }
  2139. // Quorum
  2140. if err := args.SetRawTransactionPrivateFrom(ctx, s.b, tx); err != nil {
  2141. return common.Hash{}, err
  2142. }
  2143. isPrivate, _, _, err := checkAndHandlePrivateTransaction(ctx, s.b, tx, &args.PrivateTxArgs, common.Address{}, RawTransaction)
  2144. if err != nil {
  2145. return common.Hash{}, err
  2146. }
  2147. if !isPrivate {
  2148. return common.Hash{}, fmt.Errorf("transaction is not private")
  2149. }
  2150. return SubmitTransaction(ctx, s.b, tx, args.PrivateFrom, true)
  2151. }
  2152. // DistributePrivateTransaction will perform the simulation checks and send the private transactions data to the other
  2153. // private participants
  2154. // It then submits the entire private transaction to the attached PTM and sends it to other private participants,
  2155. // return the PTM generated hash, intended to be used in the Input field of a Privacy Marker Transaction
  2156. func (s *PublicTransactionPoolAPI) DistributePrivateTransaction(ctx context.Context, encodedTx hexutil.Bytes, args SendRawTxArgs) (string, error) {
  2157. log.Info("distributing raw private tx")
  2158. tx := new(types.Transaction)
  2159. if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  2160. return "", err
  2161. }
  2162. log.Debug("deserialised raw private tx", "hash", tx.Hash())
  2163. // Quorum
  2164. if err := args.SetRawTransactionPrivateFrom(ctx, s.b, tx); err != nil {
  2165. return "", err
  2166. }
  2167. isPrivate, _, _, err := checkAndHandlePrivateTransaction(ctx, s.b, tx, &args.PrivateTxArgs, common.Address{}, RawTransaction)
  2168. if err != nil {
  2169. return "", err
  2170. }
  2171. if !isPrivate {
  2172. return "", fmt.Errorf("transaction is not private")
  2173. }
  2174. serialisedTx, err := json.Marshal(tx)
  2175. if err != nil {
  2176. return "", err
  2177. }
  2178. _, _, txnHash, err := private.P.Send(serialisedTx, args.PrivateFrom, args.PrivateFor, &engine.ExtraMetadata{})
  2179. if err != nil {
  2180. return "", err
  2181. }
  2182. log.Debug("private transaction sent to PTM", "generated ptm-hash", txnHash)
  2183. return txnHash.Hex(), nil
  2184. }
  2185. // /Quorum
  2186. // Sign calculates an ECDSA signature for:
  2187. // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  2188. //
  2189. // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  2190. // where the V value will be 27 or 28 for legacy reasons.
  2191. //
  2192. // The account associated with addr must be unlocked.
  2193. //
  2194. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  2195. func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  2196. // Look up the wallet containing the requested signer
  2197. account := accounts.Account{Address: addr}
  2198. wallet, err := s.b.AccountManager().Find(account)
  2199. if err != nil {
  2200. return nil, err
  2201. }
  2202. // Sign the requested hash with the wallet
  2203. signature, err := wallet.SignText(account, data)
  2204. if err == nil {
  2205. signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  2206. }
  2207. return signature, err
  2208. }
  2209. // SignTransactionResult represents a RLP encoded signed transaction.
  2210. type SignTransactionResult struct {
  2211. Raw hexutil.Bytes `json:"raw"`
  2212. Tx *types.Transaction `json:"tx"`
  2213. }
  2214. // SignTransaction will sign the given transaction with the from account.
  2215. // The node needs to have the private key of the account corresponding with
  2216. // the given from address and it needs to be unlocked.
  2217. func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  2218. if args.Gas == nil {
  2219. return nil, fmt.Errorf("gas not specified")
  2220. }
  2221. if args.GasPrice == nil {
  2222. return nil, fmt.Errorf("gasPrice not specified")
  2223. }
  2224. if args.Nonce == nil {
  2225. return nil, fmt.Errorf("nonce not specified")
  2226. }
  2227. // Quorum
  2228. // setDefaults calls DoEstimateGas in ethereum1.9.0, private transaction is not supported for that feature
  2229. // set gas to constant if nil
  2230. if args.IsPrivate() && args.Gas == nil {
  2231. gas := (hexutil.Uint64)(90000)
  2232. args.Gas = &gas
  2233. }
  2234. // End Quorum
  2235. if err := args.setDefaults(ctx, s.b); err != nil {
  2236. return nil, err
  2237. }
  2238. // Before actually sign the transaction, ensure the transaction fee is reasonable.
  2239. if err := checkTxFee(args.GasPrice.ToInt(), uint64(*args.Gas), s.b.RPCTxFeeCap()); err != nil {
  2240. return nil, err
  2241. }
  2242. // Quorum
  2243. toSign := args.toTransaction()
  2244. if args.IsPrivate() {
  2245. toSign.SetPrivate()
  2246. }
  2247. // End Quorum
  2248. tx, err := s.sign(args.From, toSign)
  2249. if err != nil {
  2250. return nil, err
  2251. }
  2252. data, err := tx.MarshalBinary()
  2253. if err != nil {
  2254. return nil, err
  2255. }
  2256. return &SignTransactionResult{data, tx}, nil
  2257. }
  2258. // PendingTransactions returns the transactions that are in the transaction pool
  2259. // and have a from address that is one of the accounts this node manages.
  2260. func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  2261. pending, err := s.b.GetPoolTransactions()
  2262. if err != nil {
  2263. return nil, err
  2264. }
  2265. accounts := make(map[common.Address]struct{})
  2266. for _, wallet := range s.b.AccountManager().Wallets() {
  2267. for _, account := range wallet.Accounts() {
  2268. accounts[account.Address] = struct{}{}
  2269. }
  2270. }
  2271. transactions := make([]*RPCTransaction, 0, len(pending))
  2272. for _, tx := range pending {
  2273. from, _ := types.Sender(s.signer, tx)
  2274. if _, exists := accounts[from]; exists {
  2275. transactions = append(transactions, newRPCPendingTransaction(tx))
  2276. }
  2277. }
  2278. return transactions, nil
  2279. }
  2280. // Resend accepts an existing transaction and a new gas price and limit. It will remove
  2281. // the given transaction from the pool and reinsert it with the new gas price and limit.
  2282. func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  2283. if sendArgs.Nonce == nil {
  2284. return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  2285. }
  2286. // setDefaults calls DoEstimateGas in ethereum1.9.0, private transaction is not supported for that feature
  2287. // set gas to constant if nil
  2288. if sendArgs.IsPrivate() && sendArgs.Gas == nil {
  2289. gas := (hexutil.Uint64)(90000)
  2290. sendArgs.Gas = &gas
  2291. }
  2292. if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  2293. return common.Hash{}, err
  2294. }
  2295. matchTx := sendArgs.toTransaction()
  2296. // Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  2297. var price = matchTx.GasPrice()
  2298. if gasPrice != nil {
  2299. price = gasPrice.ToInt()
  2300. }
  2301. var gas = matchTx.Gas()
  2302. if gasLimit != nil {
  2303. gas = uint64(*gasLimit)
  2304. }
  2305. if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  2306. return common.Hash{}, err
  2307. }
  2308. // Iterate the pending list for replacement
  2309. pending, err := s.b.GetPoolTransactions()
  2310. if err != nil {
  2311. return common.Hash{}, err
  2312. }
  2313. for _, p := range pending {
  2314. wantSigHash := s.signer.Hash(matchTx)
  2315. pFrom, err := types.Sender(s.signer, p)
  2316. if err == nil && pFrom == sendArgs.From && s.signer.Hash(p) == wantSigHash {
  2317. // Match. Re-sign and send the transaction.
  2318. if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  2319. sendArgs.GasPrice = gasPrice
  2320. }
  2321. if gasLimit != nil && *gasLimit != 0 {
  2322. sendArgs.Gas = gasLimit
  2323. }
  2324. newTx := sendArgs.toTransaction()
  2325. // set v param to 37 to indicate private tx before submitting to the signer.
  2326. if sendArgs.IsPrivate() {
  2327. newTx.SetPrivate()
  2328. }
  2329. signedTx, err := s.sign(sendArgs.From, newTx)
  2330. if err != nil {
  2331. return common.Hash{}, err
  2332. }
  2333. if err = s.b.SendTx(ctx, signedTx); err != nil {
  2334. return common.Hash{}, err
  2335. }
  2336. return signedTx.Hash(), nil
  2337. }
  2338. }
  2339. return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  2340. }
  2341. // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  2342. // debugging endpoint.
  2343. type PublicDebugAPI struct {
  2344. b Backend
  2345. }
  2346. // NewPublicDebugAPI creates a new API definition for the public debug methods
  2347. // of the Ethereum service.
  2348. func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  2349. return &PublicDebugAPI{b: b}
  2350. }
  2351. // GetBlockRlp retrieves the RLP encoded for of a single block.
  2352. func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  2353. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2354. if block == nil {
  2355. return "", fmt.Errorf("block #%d not found", number)
  2356. }
  2357. encoded, err := rlp.EncodeToBytes(block)
  2358. if err != nil {
  2359. return "", err
  2360. }
  2361. return fmt.Sprintf("%x", encoded), nil
  2362. }
  2363. // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  2364. // given address, returning the address of the recovered signature
  2365. //
  2366. // This is a temporary method to debug the externalsigner integration,
  2367. // TODO: Remove this method when the integration is mature
  2368. func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  2369. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2370. if block == nil {
  2371. return common.Address{}, fmt.Errorf("block #%d not found", number)
  2372. }
  2373. header := block.Header()
  2374. header.Extra = make([]byte, 32+65)
  2375. encoded := clique.CliqueRLP(header)
  2376. // Look up the wallet containing the requested signer
  2377. account := accounts.Account{Address: address}
  2378. wallet, err := api.b.AccountManager().Find(account)
  2379. if err != nil {
  2380. return common.Address{}, err
  2381. }
  2382. signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  2383. if err != nil {
  2384. return common.Address{}, err
  2385. }
  2386. sealHash := clique.SealHash(header).Bytes()
  2387. log.Info("test signing of clique block",
  2388. "Sealhash", fmt.Sprintf("%x", sealHash),
  2389. "signature", fmt.Sprintf("%x", signature))
  2390. pubkey, err := crypto.Ecrecover(sealHash, signature)
  2391. if err != nil {
  2392. return common.Address{}, err
  2393. }
  2394. var signer common.Address
  2395. copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  2396. return signer, nil
  2397. }
  2398. // PrintBlock retrieves a block and returns its pretty printed form.
  2399. func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  2400. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2401. if block == nil {
  2402. return "", fmt.Errorf("block #%d not found", number)
  2403. }
  2404. return spew.Sdump(block), nil
  2405. }
  2406. // SeedHash retrieves the seed hash of a block.
  2407. func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  2408. block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2409. if block == nil {
  2410. return "", fmt.Errorf("block #%d not found", number)
  2411. }
  2412. return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  2413. }
  2414. // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  2415. // debugging endpoint.
  2416. type PrivateDebugAPI struct {
  2417. b Backend
  2418. }
  2419. // NewPrivateDebugAPI creates a new API definition for the private debug methods
  2420. // of the Ethereum service.
  2421. func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  2422. return &PrivateDebugAPI{b: b}
  2423. }
  2424. // ChaindbProperty returns leveldb properties of the key-value database.
  2425. func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  2426. if property == "" {
  2427. property = "leveldb.stats"
  2428. } else if !strings.HasPrefix(property, "leveldb.") {
  2429. property = "leveldb." + property
  2430. }
  2431. return api.b.ChainDb().Stat(property)
  2432. }
  2433. // ChaindbCompact flattens the entire key-value database into a single level,
  2434. // removing all unused slots and merging all keys.
  2435. func (api *PrivateDebugAPI) ChaindbCompact() error {
  2436. for b := byte(0); b < 255; b++ {
  2437. log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  2438. if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  2439. log.Error("Database compaction failed", "err", err)
  2440. return err
  2441. }
  2442. }
  2443. return nil
  2444. }
  2445. // SetHead rewinds the head of the blockchain to a previous block.
  2446. func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  2447. api.b.SetHead(uint64(number))
  2448. }
  2449. // PublicNetAPI offers network related RPC methods
  2450. type PublicNetAPI struct {
  2451. net *p2p.Server
  2452. networkVersion uint64
  2453. }
  2454. // NewPublicNetAPI creates a new net API instance.
  2455. func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  2456. return &PublicNetAPI{net, networkVersion}
  2457. }
  2458. // Listening returns an indication if the node is listening for network connections.
  2459. func (s *PublicNetAPI) Listening() bool {
  2460. return true // always listening
  2461. }
  2462. // PeerCount returns the number of connected peers
  2463. func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  2464. return hexutil.Uint(s.net.PeerCount())
  2465. }
  2466. // Version returns the current ethereum protocol version.
  2467. func (s *PublicNetAPI) Version() string {
  2468. return fmt.Sprintf("%d", s.networkVersion)
  2469. }
  2470. // checkTxFee is an internal function used to check whether the fee of
  2471. // the given transaction is _reasonable_(under the cap).
  2472. func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  2473. // Short circuit if there is no cap for transaction fee at all.
  2474. if cap == 0 {
  2475. return nil
  2476. }
  2477. feeEth := new(big.Float).Quo(new(big.Float).SetInt(new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(gas))), new(big.Float).SetInt(big.NewInt(params.Ether)))
  2478. feeFloat, _ := feeEth.Float64()
  2479. if feeFloat > cap {
  2480. return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
  2481. }
  2482. return nil
  2483. }
  2484. // toHexSlice creates a slice of hex-strings based on []byte.
  2485. func toHexSlice(b [][]byte) []string {
  2486. r := make([]string, len(b))
  2487. for i := range b {
  2488. r[i] = hexutil.Encode(b[i])
  2489. }
  2490. return r
  2491. }
  2492. // Quorum
  2493. // Please note: This is a temporary integration to improve performance in high-latency
  2494. // environments when sending many private transactions. It will be removed at a later
  2495. // date when account management is handled outside Ethereum.
  2496. type AsyncSendTxArgs struct {
  2497. SendTxArgs
  2498. CallbackUrl string `json:"callbackUrl"`
  2499. }
  2500. type AsyncResultSuccess struct {
  2501. Id string `json:"id,omitempty"`
  2502. TxHash common.Hash `json:"txHash"`
  2503. }
  2504. type AsyncResultFailure struct {
  2505. Id string `json:"id,omitempty"`
  2506. Error string `json:"error"`
  2507. }
  2508. type Async struct {
  2509. sync.Mutex
  2510. sem chan struct{}
  2511. }
  2512. func (s *PublicTransactionPoolAPI) send(ctx context.Context, asyncArgs AsyncSendTxArgs) {
  2513. txHash, err := s.SendTransaction(ctx, asyncArgs.SendTxArgs)
  2514. if asyncArgs.CallbackUrl != "" {
  2515. //don't need to nil check this since id is required for every geth rpc call
  2516. //even though this is stated in the specification as an "optional" parameter
  2517. jsonId := ctx.Value("id").(*json.RawMessage)
  2518. id := string(*jsonId)
  2519. var resultResponse interface{}
  2520. if err != nil {
  2521. resultResponse = &AsyncResultFailure{Id: id, Error: err.Error()}
  2522. } else {
  2523. resultResponse = &AsyncResultSuccess{Id: id, TxHash: txHash}
  2524. }
  2525. buf := new(bytes.Buffer)
  2526. err := json.NewEncoder(buf).Encode(resultResponse)
  2527. if err != nil {
  2528. log.Info("Error encoding callback JSON", "err", err.Error())
  2529. return
  2530. }
  2531. _, err = http.Post(asyncArgs.CallbackUrl, "application/json", buf)
  2532. if err != nil {
  2533. log.Info("Error sending callback", "err", err.Error())
  2534. return
  2535. }
  2536. }
  2537. }
  2538. func newAsync(n int) *Async {
  2539. a := &Async{
  2540. sem: make(chan struct{}, n),
  2541. }
  2542. return a
  2543. }
  2544. var async = newAsync(100)
  2545. // SendTransactionAsync creates a transaction for the given argument, signs it, and
  2546. // submits it to the transaction pool. This call returns immediately to allow sending
  2547. // many private transactions/bursts of transactions without waiting for the recipient
  2548. // parties to confirm receipt of the encrypted payloads. An optional callbackUrl may
  2549. // be specified--when a transaction is submitted to the transaction pool, it will be
  2550. // called with a POST request containing either {"error": "error message"} or
  2551. // {"txHash": "0x..."}.
  2552. //
  2553. // Please note: This is a temporary integration to improve performance in high-latency
  2554. // environments when sending many private transactions. It will be removed at a later
  2555. // date when account management is handled outside Ethereum.
  2556. func (s *PublicTransactionPoolAPI) SendTransactionAsync(ctx context.Context, args AsyncSendTxArgs) (common.Hash, error) {
  2557. select {
  2558. case async.sem <- struct{}{}:
  2559. go func() {
  2560. s.send(ctx, args)
  2561. <-async.sem
  2562. }()
  2563. return common.Hash{}, nil
  2564. default:
  2565. return common.Hash{}, errors.New("too many concurrent requests")
  2566. }
  2567. }
  2568. // GetQuorumPayload returns the contents of a private transaction
  2569. func (s *PublicBlockChainAPI) GetQuorumPayload(ctx context.Context, digestHex string) (string, error) {
  2570. if !private.IsQuorumPrivacyEnabled() {
  2571. return "", fmt.Errorf("PrivateTransactionManager is not enabled")
  2572. }
  2573. psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  2574. if err != nil {
  2575. return "", err
  2576. }
  2577. if len(digestHex) < 3 {
  2578. return "", fmt.Errorf("Invalid digest hex")
  2579. }
  2580. if digestHex[:2] == "0x" {
  2581. digestHex = digestHex[2:]
  2582. }
  2583. b, err := hex.DecodeString(digestHex)
  2584. if err != nil {
  2585. return "", err
  2586. }
  2587. if len(b) != common.EncryptedPayloadHashLength {
  2588. return "", fmt.Errorf("Expected a Quorum digest of length 64, but got %d", len(b))
  2589. }
  2590. _, managedParties, data, _, err := private.P.Receive(common.BytesToEncryptedPayloadHash(b))
  2591. if err != nil {
  2592. return "", err
  2593. }
  2594. if s.b.PSMR().NotIncludeAny(psm, managedParties...) {
  2595. return "0x", nil
  2596. }
  2597. return fmt.Sprintf("0x%x", data), nil
  2598. }
  2599. func (s *PublicBlockChainAPI) GetQuorumPayloadExtra(ctx context.Context, digestHex string) (*engine.QuorumPayloadExtra, error) {
  2600. if !private.IsQuorumPrivacyEnabled() {
  2601. return nil, fmt.Errorf("PrivateTransactionManager is not enabled")
  2602. }
  2603. psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  2604. if err != nil {
  2605. return nil, err
  2606. }
  2607. if len(digestHex) < 3 {
  2608. return nil, fmt.Errorf("Invalid digest hex")
  2609. }
  2610. if digestHex[:2] == "0x" {
  2611. digestHex = digestHex[2:]
  2612. }
  2613. b, err := hex.DecodeString(digestHex)
  2614. if err != nil {
  2615. return nil, err
  2616. }
  2617. if len(b) != common.EncryptedPayloadHashLength {
  2618. return nil, fmt.Errorf("Expected a Quorum digest of length 64, but got %d", len(b))
  2619. }
  2620. _, managedParties, data, extraMetaData, err := private.P.Receive(common.BytesToEncryptedPayloadHash(b))
  2621. if err != nil {
  2622. return nil, err
  2623. }
  2624. if s.b.PSMR().NotIncludeAny(psm, managedParties...) {
  2625. return nil, nil
  2626. }
  2627. isSender := false
  2628. if len(psm.Addresses) == 0 {
  2629. isSender, _ = private.P.IsSender(common.BytesToEncryptedPayloadHash(b))
  2630. } else {
  2631. isSender = !psm.NotIncludeAny(extraMetaData.Sender)
  2632. }
  2633. return &engine.QuorumPayloadExtra{
  2634. Payload: fmt.Sprintf("0x%x", data),
  2635. ExtraMetaData: extraMetaData,
  2636. IsSender: isSender,
  2637. }, nil
  2638. }
  2639. // DecryptQuorumPayload returns the decrypted version of the input transaction
  2640. func (s *PublicBlockChainAPI) DecryptQuorumPayload(ctx context.Context, payloadHex string) (*engine.QuorumPayloadExtra, error) {
  2641. if !private.IsQuorumPrivacyEnabled() {
  2642. return nil, fmt.Errorf("PrivateTransactionManager is not enabled")
  2643. }
  2644. psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  2645. if err != nil {
  2646. return nil, err
  2647. }
  2648. if len(payloadHex) < 3 {
  2649. return nil, fmt.Errorf("Invalid payload hex")
  2650. }
  2651. if payloadHex[:2] == "0x" {
  2652. payloadHex = payloadHex[2:]
  2653. }
  2654. b, err := hex.DecodeString(payloadHex)
  2655. if err != nil {
  2656. return nil, err
  2657. }
  2658. var payload common.DecryptRequest
  2659. if err := json.Unmarshal(b, &payload); err != nil {
  2660. return nil, err
  2661. }
  2662. // if we are MPS and the sender is not part of the resolved PSM - return empty
  2663. if len(psm.Addresses) != 0 && psm.NotIncludeAny(base64.StdEncoding.EncodeToString(payload.SenderKey)) {
  2664. return nil, nil
  2665. }
  2666. data, extraMetaData, err := private.P.DecryptPayload(payload)
  2667. if err != nil {
  2668. return nil, err
  2669. }
  2670. return &engine.QuorumPayloadExtra{
  2671. Payload: fmt.Sprintf("0x%x", data),
  2672. ExtraMetaData: extraMetaData,
  2673. IsSender: true,
  2674. }, nil
  2675. }
  2676. // Quorum
  2677. // for raw private transaction, privateTxArgs.privateFrom will be updated with value from Tessera when payload is retrieved
  2678. func checkAndHandlePrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address, txnType TransactionType) (isPrivate bool, replaceDataWithHash bool, hash common.EncryptedPayloadHash, err error) {
  2679. replaceDataWithHash = false
  2680. isPrivate = privateTxArgs != nil && privateTxArgs.PrivateFor != nil
  2681. if !isPrivate {
  2682. return
  2683. }
  2684. if err = privateTxArgs.PrivacyFlag.Validate(); err != nil {
  2685. return
  2686. }
  2687. if !b.ChainConfig().IsPrivacyEnhancementsEnabled(b.CurrentBlock().Number()) && privateTxArgs.PrivacyFlag.IsNotStandardPrivate() {
  2688. err = fmt.Errorf("PrivacyEnhancements are disabled. Can only accept transactions with PrivacyFlag=0(StandardPrivate).")
  2689. return
  2690. }
  2691. if engine.PrivacyFlagMandatoryRecipients == privateTxArgs.PrivacyFlag && len(privateTxArgs.MandatoryRecipients) == 0 {
  2692. err = fmt.Errorf("missing mandatory recipients data. if no mandatory recipients required consider using PrivacyFlag=1(PartyProtection)")
  2693. return
  2694. }
  2695. if engine.PrivacyFlagMandatoryRecipients != privateTxArgs.PrivacyFlag && len(privateTxArgs.MandatoryRecipients) > 0 {
  2696. err = fmt.Errorf("privacy metadata invalid. mandatory recipients are only applicable for PrivacyFlag=2(MandatoryRecipients)")
  2697. return
  2698. }
  2699. // validate that PrivateFrom is one of the addresses of the private state resolved from the user context
  2700. if b.ChainConfig().IsMPS {
  2701. var psm *mps.PrivateStateMetadata
  2702. psm, err = b.PSMR().ResolveForUserContext(ctx)
  2703. if err != nil {
  2704. return
  2705. }
  2706. if psm.NotIncludeAny(privateTxArgs.PrivateFrom) {
  2707. err = fmt.Errorf("The PrivateFrom (%s) address does not match the specified private state (%s) ", privateTxArgs.PrivateFrom, psm.ID)
  2708. return
  2709. }
  2710. }
  2711. if len(tx.Data()) > 0 {
  2712. // check private contract exists on the node initiating the transaction
  2713. if tx.To() != nil && privateTxArgs.PrivacyFlag.IsNotStandardPrivate() {
  2714. state, _, lerr := b.StateAndHeaderByNumber(ctx, rpc.BlockNumber(b.CurrentBlock().Number().Uint64()))
  2715. if lerr != nil && state == nil {
  2716. err = fmt.Errorf("state not found")
  2717. return
  2718. }
  2719. if state.GetCode(*tx.To()) == nil {
  2720. err = fmt.Errorf("contract not found. cannot transact")
  2721. return
  2722. }
  2723. }
  2724. replaceDataWithHash = true
  2725. hash, err = handlePrivateTransaction(ctx, b, tx, privateTxArgs, from, txnType)
  2726. }
  2727. return
  2728. }
  2729. // Quorum
  2730. // If transaction is raw, the tx payload is indeed the hash of the encrypted payload.
  2731. // Then the sender key will set to privateTxArgs.privateFrom.
  2732. //
  2733. // For private transaction, run a simulated execution in order to
  2734. // 1. Find all affected private contract accounts then retrieve encrypted payload hashes of their creation txs
  2735. // 2. Calculate Merkle Root as the result of the simulated execution
  2736. // The above information along with private originating payload are sent to Transaction Manager
  2737. // to obtain hash of the encrypted private payload
  2738. func handlePrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address, txnType TransactionType) (hash common.EncryptedPayloadHash, err error) {
  2739. defer func(start time.Time) {
  2740. log.Debug("Handle Private Transaction finished", "took", time.Since(start))
  2741. }(time.Now())
  2742. data := tx.Data()
  2743. log.Debug("sending private tx", "txnType", txnType, "data", common.FormatTerminalString(data), "privatefrom", privateTxArgs.PrivateFrom, "privatefor", privateTxArgs.PrivateFor, "privacyFlag", privateTxArgs.PrivacyFlag, "mandatoryfor", privateTxArgs.MandatoryRecipients)
  2744. switch txnType {
  2745. case FillTransaction:
  2746. hash, err = private.P.StoreRaw(data, privateTxArgs.PrivateFrom)
  2747. case RawTransaction:
  2748. hash, err = handleRawPrivateTransaction(ctx, b, tx, privateTxArgs, from)
  2749. case NormalTransaction:
  2750. hash, err = handleNormalPrivateTransaction(ctx, b, tx, data, privateTxArgs, from)
  2751. }
  2752. return
  2753. }
  2754. // Quorum
  2755. func handleRawPrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address) (hash common.EncryptedPayloadHash, err error) {
  2756. data := tx.Data()
  2757. hash = common.BytesToEncryptedPayloadHash(data)
  2758. privatePayload, privateFrom, _, revErr := private.P.ReceiveRaw(hash)
  2759. if revErr != nil {
  2760. return common.EncryptedPayloadHash{}, revErr
  2761. }
  2762. log.Trace("received raw payload", "hash", hash, "privatepayload", common.FormatTerminalString(privatePayload), "privateFrom", privateFrom)
  2763. privateTxArgs.PrivateFrom = privateFrom
  2764. var privateTx *types.Transaction
  2765. if tx.To() == nil {
  2766. privateTx = types.NewContractCreation(tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), privatePayload)
  2767. } else {
  2768. privateTx = types.NewTransaction(tx.Nonce(), *tx.To(), tx.Value(), tx.Gas(), tx.GasPrice(), privatePayload)
  2769. }
  2770. affectedCATxHashes, merkleRoot, err := simulateExecutionForPE(ctx, b, from, privateTx, privateTxArgs)
  2771. log.Trace("after simulation", "affectedCATxHashes", affectedCATxHashes, "merkleRoot", merkleRoot, "privacyFlag", privateTxArgs.PrivacyFlag, "error", err)
  2772. if err != nil {
  2773. return
  2774. }
  2775. metadata := engine.ExtraMetadata{
  2776. ACHashes: affectedCATxHashes,
  2777. ACMerkleRoot: merkleRoot,
  2778. PrivacyFlag: privateTxArgs.PrivacyFlag,
  2779. MandatoryRecipients: privateTxArgs.MandatoryRecipients,
  2780. }
  2781. _, _, data, err = private.P.SendSignedTx(hash, privateTxArgs.PrivateFor, &metadata)
  2782. if err != nil {
  2783. return
  2784. }
  2785. log.Info("sent raw private signed tx",
  2786. "data", common.FormatTerminalString(data),
  2787. "hash", hash,
  2788. "privatefrom", privateTxArgs.PrivateFrom,
  2789. "privatefor", privateTxArgs.PrivateFor,
  2790. "affectedCATxHashes", metadata.ACHashes,
  2791. "merkleroot", metadata.ACHashes,
  2792. "privacyflag", metadata.PrivacyFlag,
  2793. "mandatoryrecipients", metadata.MandatoryRecipients)
  2794. return
  2795. }
  2796. // Quorum
  2797. func handleNormalPrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, data []byte, privateTxArgs *PrivateTxArgs, from common.Address) (hash common.EncryptedPayloadHash, err error) {
  2798. affectedCATxHashes, merkleRoot, err := simulateExecutionForPE(ctx, b, from, tx, privateTxArgs)
  2799. log.Trace("after simulation", "affectedCATxHashes", affectedCATxHashes, "merkleRoot", merkleRoot, "privacyFlag", privateTxArgs.PrivacyFlag, "error", err)
  2800. if err != nil {
  2801. return
  2802. }
  2803. metadata := engine.ExtraMetadata{
  2804. ACHashes: affectedCATxHashes,
  2805. ACMerkleRoot: merkleRoot,
  2806. PrivacyFlag: privateTxArgs.PrivacyFlag,
  2807. MandatoryRecipients: privateTxArgs.MandatoryRecipients,
  2808. }
  2809. _, _, hash, err = private.P.Send(data, privateTxArgs.PrivateFrom, privateTxArgs.PrivateFor, &metadata)
  2810. if err != nil {
  2811. return
  2812. }
  2813. log.Info("sent private signed tx",
  2814. "data", common.FormatTerminalString(data),
  2815. "hash", hash,
  2816. "privatefrom", privateTxArgs.PrivateFrom,
  2817. "privatefor", privateTxArgs.PrivateFor,
  2818. "affectedCATxHashes", metadata.ACHashes,
  2819. "merkleroot", metadata.ACHashes,
  2820. "privacyflag", metadata.PrivacyFlag,
  2821. "mandatoryrecipients", metadata.MandatoryRecipients)
  2822. return
  2823. }
  2824. // (Quorum) createPrivacyMarkerTransaction creates a new privacy marker transaction (PMT) with the given signed privateTx.
  2825. // The private tx is sent only to the privateFor recipients. The resulting PMT's 'to' is the privacy precompile address and its 'data' is the
  2826. // privacy manager hash for the private tx.
  2827. func createPrivacyMarkerTransaction(b Backend, privateTx *types.Transaction, privateTxArgs *PrivateTxArgs) (*types.Transaction, error) {
  2828. log.Trace("creating privacy marker transaction", "from", privateTx.From(), "to", privateTx.To())
  2829. data := new(bytes.Buffer)
  2830. err := json.NewEncoder(data).Encode(privateTx)
  2831. if err != nil {
  2832. return nil, err
  2833. }
  2834. _, _, ptmHash, err := private.P.Send(data.Bytes(), privateTxArgs.PrivateFrom, privateTxArgs.PrivateFor, &engine.ExtraMetadata{})
  2835. if err != nil {
  2836. return nil, err
  2837. }
  2838. currentBlockHeight := b.CurrentHeader().Number
  2839. istanbul := b.ChainConfig().IsIstanbul(currentBlockHeight)
  2840. intrinsicGas, err := core.IntrinsicGas(ptmHash.Bytes(), privateTx.AccessList(), false, true, istanbul)
  2841. if err != nil {
  2842. return nil, err
  2843. }
  2844. pmt := types.NewTransaction(privateTx.Nonce(), common.QuorumPrivacyPrecompileContractAddress(), privateTx.Value(), intrinsicGas, privateTx.GasPrice(), ptmHash.Bytes())
  2845. return pmt, nil
  2846. }
  2847. // Quorum
  2848. // simulateExecutionForPE simulates execution of a private transaction for enhanced privacy
  2849. //
  2850. // Returns hashes of encrypted payload of creation transactions for all affected contract accounts
  2851. // and the merkle root combining all affected contract accounts after the simulation
  2852. func simulateExecutionForPE(ctx context.Context, b Backend, from common.Address, privateTx *types.Transaction, privateTxArgs *PrivateTxArgs) (common.EncryptedPayloadHashes, common.Hash, error) {
  2853. // skip simulation if privacy enhancements are disabled
  2854. if !b.ChainConfig().IsPrivacyEnhancementsEnabled(b.CurrentBlock().Number()) {
  2855. return nil, common.Hash{}, nil
  2856. }
  2857. evm, data, err := runSimulation(ctx, b, from, privateTx)
  2858. if evm == nil {
  2859. log.Debug("TX Simulation setup failed", "error", err)
  2860. return nil, common.Hash{}, err
  2861. }
  2862. if err != nil {
  2863. if privateTxArgs.PrivacyFlag.IsStandardPrivate() {
  2864. log.Debug("An error occurred during StandardPrivate transaction simulation. "+
  2865. "Continuing to simulation checks.", "error", err)
  2866. } else {
  2867. log.Trace("Simulated execution", "error", err)
  2868. if len(data) > 0 && errors.Is(err, vm.ErrExecutionReverted) {
  2869. reason, errUnpack := abi.UnpackRevert(data)
  2870. reasonError := errors.New("execution reverted")
  2871. if errUnpack == nil {
  2872. reasonError = fmt.Errorf("execution reverted: %v", reason)
  2873. }
  2874. err = &revertError{
  2875. error: reasonError,
  2876. reason: hexutil.Encode(data),
  2877. }
  2878. }
  2879. return nil, common.Hash{}, err
  2880. }
  2881. }
  2882. affectedContractsHashes := make(common.EncryptedPayloadHashes)
  2883. var merkleRoot common.Hash
  2884. addresses := evm.AffectedContracts()
  2885. privacyFlag := privateTxArgs.PrivacyFlag
  2886. log.Trace("after simulation run", "numberOfAffectedContracts", len(addresses), "privacyFlag", privacyFlag)
  2887. for _, addr := range addresses {
  2888. // GetPrivacyMetadata is invoked directly on the privateState (as the tx is private) and it returns:
  2889. // 1. public contacts: privacyMetadata = nil, err = nil
  2890. // 2. private contracts of type:
  2891. // 2.1. StandardPrivate: privacyMetadata = nil, err = "The provided contract does not have privacy metadata"
  2892. // 2.2. PartyProtection/PSV: privacyMetadata = <data>, err = nil
  2893. privacyMetadata, err := evm.StateDB.GetPrivacyMetadata(addr)
  2894. log.Debug("Found affected contract", "address", addr.Hex(), "privacyMetadata", privacyMetadata)
  2895. //privacyMetadata not found=non-party, or another db error
  2896. if err != nil && privacyFlag.IsNotStandardPrivate() {
  2897. return nil, common.Hash{}, errors.New("PrivacyMetadata not found: " + err.Error())
  2898. }
  2899. // when we run simulation, it's possible that affected contracts may contain public ones
  2900. // public contract will not have any privacyMetadata attached
  2901. // standard private will be nil
  2902. if privacyMetadata == nil {
  2903. continue
  2904. }
  2905. //if affecteds are not all the same return an error
  2906. if privacyFlag != privacyMetadata.PrivacyFlag {
  2907. return nil, common.Hash{}, errors.New("sent privacy flag doesn't match all affected contract flags")
  2908. }
  2909. affectedContractsHashes.Add(privacyMetadata.CreationTxHash)
  2910. }
  2911. //only calculate the merkle root if all contracts are psv
  2912. if privacyFlag.Has(engine.PrivacyFlagStateValidation) {
  2913. merkleRoot, err = evm.CalculateMerkleRoot()
  2914. if err != nil {
  2915. return nil, common.Hash{}, err
  2916. }
  2917. }
  2918. log.Trace("post-execution run", "merkleRoot", merkleRoot, "affectedhashes", affectedContractsHashes)
  2919. return affectedContractsHashes, merkleRoot, nil
  2920. }
  2921. //End-Quorum