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