// NewWhisperMessage converts an internal message into an API version. func NewWhisperMessage(message *Message) WhisperMessage { return WhisperMessage{ ref: message, Payload: common.ToHex(message.Payload), From: common.ToHex(crypto.FromECDSAPub(message.Recover())), To: common.ToHex(crypto.FromECDSAPub(message.To)), Sent: message.Sent.Unix(), TTL: int64(message.TTL / time.Second), Hash: common.ToHex(message.Hash.Bytes()), } }
// NewIdentity generates a new cryptographic identity for the client, and injects // it into the known identities for message decryption. func (s *PublicWhisperAPI) NewIdentity() (string, error) { if s.w == nil { return "", whisperOffLineErr } identity := s.w.NewIdentity() return common.ToHex(crypto.FromECDSAPub(&identity.PublicKey)), nil }
func (s *PublicBlockChainAPI) doCall(args CallArgs, blockNr rpc.BlockNumber) (string, *big.Int, error) { if block := blockByNumber(s.miner, s.bc, blockNr); block != nil { stateDb, err := state.New(block.Root(), s.chainDb) if err != nil { return "0x", nil, err } stateDb = stateDb.Copy() var from *state.StateObject if args.From == (common.Address{}) { accounts, err := s.am.Accounts() if err != nil || len(accounts) == 0 { from = stateDb.GetOrNewStateObject(common.Address{}) } else { from = stateDb.GetOrNewStateObject(accounts[0].Address) } } else { from = stateDb.GetOrNewStateObject(args.From) } from.SetBalance(common.MaxBig) msg := callmsg{ from: from, to: &args.To, gas: args.Gas.BigInt(), gasPrice: args.GasPrice.BigInt(), value: args.Value.BigInt(), data: common.FromHex(args.Data), } if msg.gas.Cmp(common.Big0) == 0 { msg.gas = big.NewInt(50000000) } if msg.gasPrice.Cmp(common.Big0) == 0 { msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon) } header := s.bc.CurrentBlock().Header() vmenv := core.NewEnv(stateDb, s.bc, msg, header) gp := new(core.GasPool).AddGas(common.MaxBig) res, gas, err := core.ApplyMessage(vmenv, msg, gp) if len(res) == 0 { // backwards compatability return "0x", gas, err } return common.ToHex(res), gas, err } return "0x", common.Big0, nil }
// GetData returns the data stored at the given address in the state for the given block number. func (s *PublicBlockChainAPI) GetData(address common.Address, blockNr rpc.BlockNumber) (string, error) { if block := blockByNumber(s.miner, s.bc, blockNr); block != nil { state, err := state.New(block.Root(), s.chainDb) if err != nil { return "", err } res := state.GetCode(address) if len(res) == 0 { // backwards compatibility return "0x", nil } return common.ToHex(res), nil } return "0x", nil }
// Call forms a transaction from the given arguments and tries to execute it on // a private VM with a copy of the state. Any changes are therefore only temporary // and not part of the actual state. This allows for local execution/queries. func (be *registryAPIBackend) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, string, error) { block := be.bc.CurrentBlock() statedb, err := state.New(block.Root(), be.chainDb) if err != nil { return "", "", err } var from *state.StateObject if len(fromStr) == 0 { accounts, err := be.am.Accounts() if err != nil || len(accounts) == 0 { from = statedb.GetOrNewStateObject(common.Address{}) } else { from = statedb.GetOrNewStateObject(accounts[0].Address) } } else { from = statedb.GetOrNewStateObject(common.HexToAddress(fromStr)) } from.SetBalance(common.MaxBig) msg := callmsg{ from: from, gas: common.Big(gasStr), gasPrice: common.Big(gasPriceStr), value: common.Big(valueStr), data: common.FromHex(dataStr), } if len(toStr) > 0 { addr := common.HexToAddress(toStr) msg.to = &addr } if msg.gas.Cmp(big.NewInt(0)) == 0 { msg.gas = big.NewInt(50000000) } if msg.gasPrice.Cmp(big.NewInt(0)) == 0 { msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon) } header := be.bc.CurrentBlock().Header() vmenv := core.NewEnv(statedb, be.bc, msg, header) gp := new(core.GasPool).AddGas(common.MaxBig) res, gas, err := core.ApplyMessage(vmenv, msg, gp) return common.ToHex(res), gas.String(), err }
// Sha3 applies the ethereum sha3 implementation on the input. // It assumes the input is hex encoded. func (s *PublicWeb3API) Sha3(input string) string { return common.ToHex(crypto.Sha3(common.FromHex(input))) }
func abiSignature(s string) string { return common.ToHex(crypto.Sha3([]byte(s))[:4]) }
func storageAddress(addr []byte) string { return common.ToHex(addr) }
func main() { // Parse and handle the command line flags flag.Parse() log15.Root().SetHandler(log15.LvlFilterHandler(log15.Lvl(*loglevelFlag), log15.StderrHandler)) datadir := *datadirFlag if datadir == "" { datadir = filepath.Join(os.Getenv("HOME"), ".etherapis") } if err := os.MkdirAll(datadir, 0700); err != nil { log15.Crit("Failed to create data directory: %v", err) return } // Assemble and start the Ethereum client log15.Info("Booting Ethereum client...") client, err := geth.New(datadir, geth.TestNet) if err != nil { log15.Crit("Failed to create Ethereum client", "error", err) return } if err := client.Start(); err != nil { log15.Crit("Failed to start Ethereum client", "error", err) return } api, err := client.Attach() if err != nil { log15.Crit("Failed to attach to node", "error", err) return } // Wait for network connectivity and monitor synchronization log15.Info("Searching for network peers...") server := client.Stack().Server() for len(server.Peers()) == 0 { time.Sleep(100 * time.Millisecond) } go monitorSync(api) // Make sure we're at least semi recent on the chain before continuing waitSync(*syncFlag, api) var eth *eth.Ethereum err = client.Stack().Service(ð) if err != nil { log15.Crit("Failed to fetch eth service", "error", err) return } contract, err := channels.Fetch(eth.ChainDb(), eth.EventMux(), eth.BlockChain()) if err != nil { log15.Crit("Failed to get contract", "error", err) return } // Depending on the flags, execute different things switch { case *signFlag != "": var message struct { Provider string Nonce uint64 Amount uint64 } if err := json.Unmarshal([]byte(*signFlag), &message); err != nil { log15.Crit("Failed to decode data", "error", err) return } fmt.Println(message) accounts, err := eth.AccountManager().Accounts() if err != nil { log15.Crit("Failed retrieving accounts", "err", err) } if len(accounts) == 0 { log15.Crit("Signing data requires at least one account", "len", len(accounts)) return } account := accounts[0] from := account.Address to := common.HexToAddress(message.Provider) hash := contract.Call("getHash", from, to, message.Nonce, message.Amount).([]byte) log15.Info("getting hash", "hash", common.ToHex(hash)) eth.AccountManager().Unlock(from, "") sig, err := eth.AccountManager().Sign(account, hash) if err != nil { log15.Crit("signing vailed", "err", err) return } log15.Info("generated signature", "sig", common.ToHex(sig)) return case *importFlag != "": // Account import, parse the provided .json file and ensure it's proper manager := eth.AccountManager() account, err := manager.Import(*importFlag, "") if err != nil { log15.Crit("Failed to import specified account", "path", *importFlag, "error", err) return } state, _ := eth.BlockChain().State() log15.Info("Account successfully imported", "account", fmt.Sprintf("0x%x", account.Address), "balance", state.GetBalance(account.Address)) return case *accountsFlag: // Account listing requested, print all accounts and balances accounts, err := eth.AccountManager().Accounts() if err != nil || len(accounts) == 0 { log15.Crit("Failed to retrieve account", "accounts", len(accounts), "error", err) return } state, _ := eth.BlockChain().State() for i, account := range accounts { balance := float64(new(big.Int).Div(state.GetBalance(account.Address), common.Finney).Int64()) / 1000 fmt.Printf("Account #%d: %f ether (http://testnet.etherscan.io/address/0x%x)\n", i, balance, account.Address) } return case *accGenFlag > 0: // We're generating and dumping demo accounts var nonce uint64 var bank accounts.Account if *accLiveFlag { // If we want to fund generated accounts, make sure we can accounts, err := eth.AccountManager().Accounts() if err != nil || len(accounts) == 0 { log15.Crit("Failed to retrieve funding account", "accounts", len(accounts), "error", err) return } bank = accounts[0] if err := eth.AccountManager().Unlock(bank.Address, "gophergala"); err != nil { log15.Crit("Failed to unlock funding account", "account", fmt.Sprintf("0x%x", bank.Address), "error", err) return } state, _ := eth.BlockChain().State() nonce = state.GetNonce(bank.Address) log15.Info("Funding demo accounts with", "bank", fmt.Sprintf("0x%x", bank.Address), "nonce", nonce) } // Start generating the actual accounts log15.Info("Generating demo accounts", "count", *accGenFlag) for i := 0; i < *accGenFlag; i++ { // Generate a new account account, err := eth.AccountManager().NewAccount("pass") if err != nil { log15.Crit("Failed to generate new account", "error", err) return } // Export it's private key keyPath := fmt.Sprintf("0x%x.key", account.Address) if err := eth.AccountManager().Export(keyPath, account.Address, "pass"); err != nil { log15.Crit("Failed to export account", "account", fmt.Sprintf("0x%x", account.Address), "error", err) return } // Clean up so it doesn't clutter out accounts if err := eth.AccountManager().DeleteAccount(account.Address, "pass"); err != nil { log15.Crit("Failed to delete account", "account", fmt.Sprintf("0x%x", account.Address), "error", err) return } // If we're just testing, stop here if !*accLiveFlag { log15.Info("Account generated and exported", "path", keyPath) continue } // Oh boy, live accounts, send some ether to it and upload to the faucet allowance := new(big.Int).Mul(big.NewInt(10), common.Ether) price := new(big.Int).Mul(big.NewInt(50), common.Shannon) tx := types.NewTransaction(nonce, account.Address, allowance, big.NewInt(21000), price, nil) sig, err := eth.AccountManager().Sign(bank, tx.SigHash().Bytes()) if err != nil { log15.Crit("Failed to sign funding transaction", "error", err) return } stx, err := tx.WithSignature(sig) if err != nil { log15.Crit("Failed to assemble funding transaction", "error", err) return } if err := eth.TxPool().Add(stx); err != nil { log15.Crit("Failed to execute transfer", "error", err) return } nonce++ log15.Info("Account successfully funded", "account", fmt.Sprintf("0x%x", account.Address)) // Upload the account to the faucet server key, err := ioutil.ReadFile(keyPath) if err != nil { log15.Crit("Failed to load private key", "error", err) return } res, err := http.Get("https://etherapis.appspot.com/faucet/fund?key=" + string(key)) if err != nil { log15.Crit("Failed to upload private key to faucet", "error", err) return } res.Body.Close() log15.Info("Account uploaded to faucet", "account", fmt.Sprintf("0x%x", account.Address)) os.Remove(keyPath) } // Just wait a bit to ensure transactions get propagated into the network log15.Info("Sleeping to ensure transaction propagation") time.Sleep(10 * time.Second) return case len(*queryFlag) > 0: // Check whether any of our accounts are subscribed to this particular service accounts, err := eth.AccountManager().Accounts() if err != nil || len(accounts) == 0 { log15.Crit("Failed to retrieve account", "accounts", len(accounts), "error", err) return } provider := common.HexToAddress(*queryFlag) log15.Info("Checking subscription status", "service", fmt.Sprintf("0x%x", provider)) for i, account := range accounts { // Check if a subscription exists if !contract.Exists(account.Address, provider) { fmt.Printf("Account #%d: [0x%x]: not subscribed.\n", i, account.Address) continue } // Retrieve the current balance on the subscription ethers := contract.Call("getChannelValue", contract.ChannelId(account.Address, provider)).(*big.Int) funds := float64(new(big.Int).Div(ethers, common.Finney).Int64()) / 1000 fmt.Printf("Account #%d: [0x%x]: subscribed, with %v ether(s) left.\n", i, account.Address, funds) } return case len(*subToFlag) > 0: // Subscription requested, make sure all the details are provided accounts, err := eth.AccountManager().Accounts() if err != nil || len(accounts) < *subAccFlag { log15.Crit("Failed to retrieve account", "accounts", len(accounts), "requested", *subAccFlag, "error", err) return } account := accounts[*subAccFlag] // Check if a subscription exists provider := common.HexToAddress(*subToFlag) if contract.Exists(account.Address, provider) { log15.Error("Account already subscribed", "index", *subAccFlag, "account", fmt.Sprintf("0x%x", account.Address), "service", fmt.Sprintf("0x%x", provider)) return } // Try to subscribe and wait until it completes keystore := client.Keystore() key, err := keystore.GetKey(account.Address, "") if err != nil { log15.Crit("Failed to unlock account", "account", fmt.Sprintf("0x%x", account.Address), "error", err) return } amount := new(big.Int).Mul(big.NewInt(int64(1000000000**subFundFlag)), common.Shannon) log15.Info("Subscribing to new payment channel", "account", fmt.Sprintf("0x%x", account.Address), "service", fmt.Sprintf("0x%x", provider), "ethers", *subFundFlag) pend := make(chan *channels.Channel) tx, err := contract.NewChannel(key.PrivateKey, provider, amount, big.NewInt(1), func(sub *channels.Channel) { pend <- sub }) if err != nil { log15.Crit("Failed to create subscription", "error", err) return } if err := eth.TxPool().Add(tx); err != nil { log15.Crit("Failed to execute subscription", "error", err) return } log15.Info("Waiting for subscription to be finalized...", "tx", tx) log15.Info("Successfully subscribed", "channel", fmt.Sprintf("%x", (<-pend).Id)) return } if *testFlag { accounts, err := eth.AccountManager().Accounts() if err != nil { log15.Crit("Failed retrieving accounts", "err", err) } if len(accounts) < 2 { log15.Crit("Test vectors requires at least 2 accounts", "len", len(accounts)) return } log15.Info("Attempting channel test vectors...") from := accounts[0].Address eth.AccountManager().Unlock(from, "") to := accounts[0].Address log15.Info("making channel name...", "from", from.Hex(), "to", to.Hex(), "ID", contract.ChannelId(from, to).Hex()) log15.Info("checking existence...", "exists", contract.Exists(from, to)) amount := big.NewInt(1) hash := contract.Call("getHash", from, to, 0, amount).([]byte) log15.Info("signing data", "to", to.Hex(), "amount", amount, "hash", common.ToHex(hash)) sig, err := eth.AccountManager().Sign(accounts[0], hash) if err != nil { log15.Crit("signing vailed", "err", err) return } log15.Info("verifying signature", "sig", common.ToHex(sig)) if contract.ValidateSig(from, to, 0, amount, sig) { log15.Info("signature was valid and was verified by the EVM") } else { log15.Crit("signature was invalid") return } log15.Info("verifying payment", "sig", common.ToHex(sig)) if valid, _ := contract.Verify(from, to, 0, amount, sig); valid { log15.Info("payment was valid and was verified by the EVM") } else { log15.Crit("payment was invalid") return } log15.Info("verifying invalid payment", "nonce", 1) if valid, _ := contract.Verify(from, to, 1, amount, sig); valid { log15.Crit("payment was valid") return } else { log15.Info("payment was invalid") } } // If we're running a proxy, start processing external requests if *proxyFlag != "" { // Subscription requested, make sure all the details are provided accounts, err := eth.AccountManager().Accounts() if err != nil || len(accounts) < *subAccFlag { log15.Crit("Failed to retrieve account", "accounts", len(accounts), "requested", *subAccFlag, "error", err) return } account := accounts[*subAccFlag] if err := eth.AccountManager().Unlock(account.Address, ""); err != nil { log15.Crit("Failed to unlock provider account", "account", fmt.Sprintf("0x%x", account.Address), "error", err) return } log15.Info("Setuping vault...", "owner", account.Address.Hex()) // Create the payment vault to hold the various authorizations vault := proxy.NewVault(NewCharger(account, eth.TxPool(), contract, eth.AccountManager())) vault.AutoCharge(*chargeFlag) for i, config := range strings.Split(*proxyFlag, ",") { // Split the proxy configuration parts := strings.Split(config, ":") if len(parts) != 3 { log15.Crit("Invalid proxy config", "config", config) return } extPort, err := strconv.Atoi(parts[0]) if err != nil || extPort < 0 || extPort > 65535 { log15.Crit("Invalid external port number", "port", parts[0]) return } intPort, err := strconv.Atoi(parts[1]) if err != nil || intPort < 0 || intPort > 65535 { log15.Crit("Invalid internal port number", "port", parts[1]) return } var kind proxy.ProxyType switch strings.ToLower(parts[2]) { case "call": kind = proxy.CallProxy case "data": kind = proxy.DataProxy default: log15.Crit("Unsupported proxy type", "type", parts[2], "allowed", []string{"call", "data"}) return } // Create and start the new proxy gateway := proxy.New(i, extPort, intPort, kind, contract, vault) go func() { if err := gateway.Start(); err != nil { log15.Crit("Failed to start proxy", "error", err) os.Exit(-1) } }() } // Wait indefinitely, for now at least for { time.Sleep(time.Second) } } // Clean up for now log15.Info("Terminating Ethereum client...") if err := client.Stop(); err != nil { log15.Crit("Failed to terminate Ethereum client", "error", err) return } }
// Sign will sign the given data string with the given address. The account corresponding with the address needs to // be unlocked. func (s *PublicTransactionPoolAPI) Sign(address common.Address, data string) (string, error) { signature, error := s.am.Sign(accounts.Account{Address: address}, common.HexToHash(data).Bytes()) return common.ToHex(signature), error }