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