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