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