github.com/newbtp/btp@v0.0.0-20190709081714-e4aafa07224e/cmd/faucet/faucet.go (about) 1 // Copyright 2017 The go-btpereum Authors 2 // This file is part of go-btpereum. 3 // 4 // go-btpereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU 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 // go-btpereum 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 General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-btpereum. If not, see <http://www.gnu.org/licenses/>. 16 17 // faucet is a btper faucet backed by a light client. 18 package main 19 20 //go:generate go-bindata -nometadata -o website.go faucet.html 21 //go:generate gofmt -w -s website.go 22 23 import ( 24 "bytes" 25 "context" 26 "encoding/json" 27 "errors" 28 "flag" 29 "fmt" 30 "html/template" 31 "io/ioutil" 32 "math" 33 "math/big" 34 "net/http" 35 "net/url" 36 "os" 37 "path/filepath" 38 "regexp" 39 "strconv" 40 "strings" 41 "sync" 42 "time" 43 44 "github.com/btpereum/go-btpereum/accounts" 45 "github.com/btpereum/go-btpereum/accounts/keystore" 46 "github.com/btpereum/go-btpereum/common" 47 "github.com/btpereum/go-btpereum/core" 48 "github.com/btpereum/go-btpereum/core/types" 49 "github.com/btpereum/go-btpereum/btp" 50 "github.com/btpereum/go-btpereum/btp/downloader" 51 "github.com/btpereum/go-btpereum/btpclient" 52 "github.com/btpereum/go-btpereum/btpstats" 53 "github.com/btpereum/go-btpereum/les" 54 "github.com/btpereum/go-btpereum/log" 55 "github.com/btpereum/go-btpereum/node" 56 "github.com/btpereum/go-btpereum/p2p" 57 "github.com/btpereum/go-btpereum/p2p/discv5" 58 "github.com/btpereum/go-btpereum/p2p/enode" 59 "github.com/btpereum/go-btpereum/p2p/nat" 60 "github.com/btpereum/go-btpereum/params" 61 "golang.org/x/net/websocket" 62 ) 63 64 var ( 65 genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with") 66 apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection") 67 btpPortFlag = flag.Int("btpport", 30303, "Listener port for the devp2p connection") 68 bootFlag = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with") 69 netFlag = flag.Uint64("network", 0, "Network ID to use for the btpereum protocol") 70 statsFlag = flag.String("btpstats", "", "btpstats network monitoring auth string") 71 72 netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet") 73 payoutFlag = flag.Int("faucet.amount", 1, "Number of btpers to pay out per user request") 74 minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds") 75 tiersFlag = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)") 76 77 accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with") 78 accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds") 79 80 captchaToken = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side") 81 captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side") 82 83 noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication") 84 logFlag = flag.Int("loglevel", 3, "Log level to use for btpereum and the faucet") 85 ) 86 87 var ( 88 btper = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) 89 ) 90 91 var ( 92 gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags) 93 gitDate = "" // Git commit date YYYYMMDD of the release (set via linker flags) 94 ) 95 96 func main() { 97 // Parse the flags and set up the logger to print everything requested 98 flag.Parse() 99 log.Root().Sbtpandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) 100 101 // Construct the payout tiers 102 amounts := make([]string, *tiersFlag) 103 periods := make([]string, *tiersFlag) 104 for i := 0; i < *tiersFlag; i++ { 105 // Calculate the amount for the next tier and format it 106 amount := float64(*payoutFlag) * math.Pow(2.5, float64(i)) 107 amounts[i] = fmt.Sprintf("%s btpers", strconv.FormatFloat(amount, 'f', -1, 64)) 108 if amount == 1 { 109 amounts[i] = strings.TrimSuffix(amounts[i], "s") 110 } 111 // Calculate the period for the next tier and format it 112 period := *minutesFlag * int(math.Pow(3, float64(i))) 113 periods[i] = fmt.Sprintf("%d mins", period) 114 if period%60 == 0 { 115 period /= 60 116 periods[i] = fmt.Sprintf("%d hours", period) 117 118 if period%24 == 0 { 119 period /= 24 120 periods[i] = fmt.Sprintf("%d days", period) 121 } 122 } 123 if period == 1 { 124 periods[i] = strings.TrimSuffix(periods[i], "s") 125 } 126 } 127 // Load up and render the faucet website 128 tmpl, err := Asset("faucet.html") 129 if err != nil { 130 log.Crit("Failed to load the faucet template", "err", err) 131 } 132 website := new(bytes.Buffer) 133 err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{ 134 "Network": *netnameFlag, 135 "Amounts": amounts, 136 "Periods": periods, 137 "Recaptcha": *captchaToken, 138 "NoAuth": *noauthFlag, 139 }) 140 if err != nil { 141 log.Crit("Failed to render the faucet template", "err", err) 142 } 143 // Load and parse the genesis block requested by the user 144 blob, err := ioutil.ReadFile(*genesisFlag) 145 if err != nil { 146 log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err) 147 } 148 genesis := new(core.Genesis) 149 if err = json.Unmarshal(blob, genesis); err != nil { 150 log.Crit("Failed to parse genesis block json", "err", err) 151 } 152 // Convert the bootnodes to internal enode representations 153 var enodes []*discv5.Node 154 for _, boot := range strings.Split(*bootFlag, ",") { 155 if url, err := discv5.ParseNode(boot); err == nil { 156 enodes = append(enodes, url) 157 } else { 158 log.Error("Failed to parse bootnode URL", "url", boot, "err", err) 159 } 160 } 161 // Load up the account key and decrypt its password 162 if blob, err = ioutil.ReadFile(*accPassFlag); err != nil { 163 log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err) 164 } 165 // Delete trailing newline in password 166 pass := strings.TrimSuffix(string(blob), "\n") 167 168 ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP) 169 if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil { 170 log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err) 171 } 172 acc, err := ks.Import(blob, pass, pass) 173 if err != nil { 174 log.Crit("Failed to import faucet signer account", "err", err) 175 } 176 ks.Unlock(acc, pass) 177 178 // Assemble and start the faucet light service 179 faucet, err := newFaucet(genesis, *btpPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes()) 180 if err != nil { 181 log.Crit("Failed to start faucet", "err", err) 182 } 183 defer faucet.close() 184 185 if err := faucet.listenAndServe(*apiPortFlag); err != nil { 186 log.Crit("Failed to launch faucet API", "err", err) 187 } 188 } 189 190 // request represents an accepted funding request. 191 type request struct { 192 Avatar string `json:"avatar"` // Avatar URL to make the UI nicer 193 Account common.Address `json:"account"` // btpereum address being funded 194 Time time.Time `json:"time"` // Timestamp when the request was accepted 195 Tx *types.Transaction `json:"tx"` // Transaction funding the account 196 } 197 198 // faucet represents a crypto faucet backed by an btpereum light client. 199 type faucet struct { 200 config *params.ChainConfig // Chain configurations for signing 201 stack *node.Node // btpereum protocol stack 202 client *btpclient.Client // Client connection to the btpereum chain 203 index []byte // Index page to serve up on the web 204 205 keystore *keystore.KeyStore // Keystore containing the single signer 206 account accounts.Account // Account funding user faucet requests 207 head *types.Header // Current head header of the faucet 208 balance *big.Int // Current balance of the faucet 209 nonce uint64 // Current pending nonce of the faucet 210 price *big.Int // Current gas price to issue funds with 211 212 conns []*websocket.Conn // Currently live websocket connections 213 timeouts map[string]time.Time // History of users and their funding timeouts 214 reqs []*request // Currently pending funding requests 215 update chan struct{} // Channel to signal request updates 216 217 lock sync.RWMutex // Lock protecting the faucet's internals 218 } 219 220 func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) { 221 // Assemble the raw devp2p protocol stack 222 stack, err := node.New(&node.Config{ 223 Name: "gbtp", 224 Version: params.VersionWithCommit(gitCommit, gitDate), 225 DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"), 226 P2P: p2p.Config{ 227 NAT: nat.Any(), 228 NoDiscovery: true, 229 DiscoveryV5: true, 230 ListenAddr: fmt.Sprintf(":%d", port), 231 MaxPeers: 25, 232 BootstrapNodesV5: enodes, 233 }, 234 }) 235 if err != nil { 236 return nil, err 237 } 238 // Assemble the btpereum light client protocol 239 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 240 cfg := btp.DefaultConfig 241 cfg.SyncMode = downloader.LightSync 242 cfg.NetworkId = network 243 cfg.Genesis = genesis 244 return les.New(ctx, &cfg) 245 }); err != nil { 246 return nil, err 247 } 248 // Assemble the btpstats monitoring and reporting service' 249 if stats != "" { 250 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 251 var serv *les.Lightbtpereum 252 ctx.Service(&serv) 253 return btpstats.New(stats, nil, serv) 254 }); err != nil { 255 return nil, err 256 } 257 } 258 // Boot up the client and ensure it connects to bootnodes 259 if err := stack.Start(); err != nil { 260 return nil, err 261 } 262 for _, boot := range enodes { 263 old, err := enode.Parse(enode.ValidSchemes, boot.String()) 264 if err == nil { 265 stack.Server().AddPeer(old) 266 } 267 } 268 // Attach to the client and retrieve and interesting metadatas 269 api, err := stack.Attach() 270 if err != nil { 271 stack.Stop() 272 return nil, err 273 } 274 client := btpclient.NewClient(api) 275 276 return &faucet{ 277 config: genesis.Config, 278 stack: stack, 279 client: client, 280 index: index, 281 keystore: ks, 282 account: ks.Accounts()[0], 283 timeouts: make(map[string]time.Time), 284 update: make(chan struct{}, 1), 285 }, nil 286 } 287 288 // close terminates the btpereum connection and tears down the faucet. 289 func (f *faucet) close() error { 290 return f.stack.Close() 291 } 292 293 // listenAndServe registers the HTTP handlers for the faucet and boots it up 294 // for service user funding requests. 295 func (f *faucet) listenAndServe(port int) error { 296 go f.loop() 297 298 http.HandleFunc("/", f.webHandler) 299 http.Handle("/api", websocket.Handler(f.apiHandler)) 300 301 return http.ListenAndServe(fmt.Sprintf(":%d", port), nil) 302 } 303 304 // webHandler handles all non-api requests, simply flattening and returning the 305 // faucet website. 306 func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) { 307 w.Write(f.index) 308 } 309 310 // apiHandler handles requests for btper grants and transaction statuses. 311 func (f *faucet) apiHandler(conn *websocket.Conn) { 312 // Start tracking the connection and drop at the end 313 defer conn.Close() 314 315 f.lock.Lock() 316 f.conns = append(f.conns, conn) 317 f.lock.Unlock() 318 319 defer func() { 320 f.lock.Lock() 321 for i, c := range f.conns { 322 if c == conn { 323 f.conns = append(f.conns[:i], f.conns[i+1:]...) 324 break 325 } 326 } 327 f.lock.Unlock() 328 }() 329 // Gather the initial stats from the network to report 330 var ( 331 head *types.Header 332 balance *big.Int 333 nonce uint64 334 err error 335 ) 336 for head == nil || balance == nil { 337 // Retrieve the current stats cached by the faucet 338 f.lock.RLock() 339 if f.head != nil { 340 head = types.CopyHeader(f.head) 341 } 342 if f.balance != nil { 343 balance = new(big.Int).Set(f.balance) 344 } 345 nonce = f.nonce 346 f.lock.RUnlock() 347 348 if head == nil || balance == nil { 349 // Report the faucet offline until initial stats are ready 350 if err = sendError(conn, errors.New("Faucet offline")); err != nil { 351 log.Warn("Failed to send faucet error to client", "err", err) 352 return 353 } 354 time.Sleep(3 * time.Second) 355 } 356 } 357 // Send over the initial stats and the latest header 358 if err = send(conn, map[string]interface{}{ 359 "funds": new(big.Int).Div(balance, btper), 360 "funded": nonce, 361 "peers": f.stack.Server().PeerCount(), 362 "requests": f.reqs, 363 }, 3*time.Second); err != nil { 364 log.Warn("Failed to send initial stats to client", "err", err) 365 return 366 } 367 if err = send(conn, head, 3*time.Second); err != nil { 368 log.Warn("Failed to send initial header to client", "err", err) 369 return 370 } 371 // Keep reading requests from the websocket until the connection breaks 372 for { 373 // Fetch the next funding request and validate against github 374 var msg struct { 375 URL string `json:"url"` 376 Tier uint `json:"tier"` 377 Captcha string `json:"captcha"` 378 } 379 if err = websocket.JSON.Receive(conn, &msg); err != nil { 380 return 381 } 382 if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") && 383 !strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") { 384 if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil { 385 log.Warn("Failed to send URL error to client", "err", err) 386 return 387 } 388 continue 389 } 390 if msg.Tier >= uint(*tiersFlag) { 391 if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil { 392 log.Warn("Failed to send tier error to client", "err", err) 393 return 394 } 395 continue 396 } 397 log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier) 398 399 // If captcha verifications are enabled, make sure we're not dealing with a robot 400 if *captchaToken != "" { 401 form := url.Values{} 402 form.Add("secret", *captchaSecret) 403 form.Add("response", msg.Captcha) 404 405 res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form) 406 if err != nil { 407 if err = sendError(conn, err); err != nil { 408 log.Warn("Failed to send captcha post error to client", "err", err) 409 return 410 } 411 continue 412 } 413 var result struct { 414 Success bool `json:"success"` 415 Errors json.RawMessage `json:"error-codes"` 416 } 417 err = json.NewDecoder(res.Body).Decode(&result) 418 res.Body.Close() 419 if err != nil { 420 if err = sendError(conn, err); err != nil { 421 log.Warn("Failed to send captcha decode error to client", "err", err) 422 return 423 } 424 continue 425 } 426 if !result.Success { 427 log.Warn("Captcha verification failed", "err", string(result.Errors)) 428 if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil { 429 log.Warn("Failed to send captcha failure to client", "err", err) 430 return 431 } 432 continue 433 } 434 } 435 // Retrieve the btpereum address to fund, the requesting user and a profile picture 436 var ( 437 username string 438 avatar string 439 address common.Address 440 ) 441 switch { 442 case strings.HasPrefix(msg.URL, "https://gist.github.com/"): 443 if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil { 444 log.Warn("Failed to send GitHub deprecation to client", "err", err) 445 return 446 } 447 continue 448 case strings.HasPrefix(msg.URL, "https://plus.google.com/"): 449 if err = sendError(conn, errors.New("Google+ authentication discontinued as the service was sunset")); err != nil { 450 log.Warn("Failed to send Google+ deprecation to client", "err", err) 451 return 452 } 453 continue 454 case strings.HasPrefix(msg.URL, "https://twitter.com/"): 455 username, avatar, address, err = authTwitter(msg.URL) 456 case strings.HasPrefix(msg.URL, "https://www.facebook.com/"): 457 username, avatar, address, err = authFacebook(msg.URL) 458 case *noauthFlag: 459 username, avatar, address, err = authNoAuth(msg.URL) 460 default: 461 err = errors.New("Sombtping funky happened, please open an issue at https://github.com/btpereum/go-btpereum/issues") 462 } 463 if err != nil { 464 if err = sendError(conn, err); err != nil { 465 log.Warn("Failed to send prefix error to client", "err", err) 466 return 467 } 468 continue 469 } 470 log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address) 471 472 // Ensure the user didn't request funds too recently 473 f.lock.Lock() 474 var ( 475 fund bool 476 timeout time.Time 477 ) 478 if timeout = f.timeouts[username]; time.Now().After(timeout) { 479 // User wasn't funded recently, create the funding transaction 480 amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), btper) 481 amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil)) 482 amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil)) 483 484 tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil) 485 signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainID) 486 if err != nil { 487 f.lock.Unlock() 488 if err = sendError(conn, err); err != nil { 489 log.Warn("Failed to send transaction creation error to client", "err", err) 490 return 491 } 492 continue 493 } 494 // Submit the transaction and mark as funded if successful 495 if err := f.client.SendTransaction(context.Background(), signed); err != nil { 496 f.lock.Unlock() 497 if err = sendError(conn, err); err != nil { 498 log.Warn("Failed to send transaction transmission error to client", "err", err) 499 return 500 } 501 continue 502 } 503 f.reqs = append(f.reqs, &request{ 504 Avatar: avatar, 505 Account: address, 506 Time: time.Now(), 507 Tx: signed, 508 }) 509 f.timeouts[username] = time.Now().Add(time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute) 510 fund = true 511 } 512 f.lock.Unlock() 513 514 // Send an error if too frequent funding, othewise a success 515 if !fund { 516 if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(timeout.Sub(time.Now())))); err != nil { // nolint: gosimple 517 log.Warn("Failed to send funding error to client", "err", err) 518 return 519 } 520 continue 521 } 522 if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil { 523 log.Warn("Failed to send funding success to client", "err", err) 524 return 525 } 526 select { 527 case f.update <- struct{}{}: 528 default: 529 } 530 } 531 } 532 533 // refresh attempts to retrieve the latest header from the chain and extract the 534 // associated faucet balance and nonce for connectivity caching. 535 func (f *faucet) refresh(head *types.Header) error { 536 // Ensure a state update does not run for too long 537 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 538 defer cancel() 539 540 // If no header was specified, use the current chain head 541 var err error 542 if head == nil { 543 if head, err = f.client.HeaderByNumber(ctx, nil); err != nil { 544 return err 545 } 546 } 547 // Retrieve the balance, nonce and gas price from the current head 548 var ( 549 balance *big.Int 550 nonce uint64 551 price *big.Int 552 ) 553 if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil { 554 return err 555 } 556 if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil { 557 return err 558 } 559 if price, err = f.client.SuggestGasPrice(ctx); err != nil { 560 return err 561 } 562 // Everything succeeded, update the cached stats and eject old requests 563 f.lock.Lock() 564 f.head, f.balance = head, balance 565 f.price, f.nonce = price, nonce 566 for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce { 567 f.reqs = f.reqs[1:] 568 } 569 f.lock.Unlock() 570 571 return nil 572 } 573 574 // loop keeps waiting for interesting events and pushes them out to connected 575 // websockets. 576 func (f *faucet) loop() { 577 // Wait for chain events and push them to clients 578 heads := make(chan *types.Header, 16) 579 sub, err := f.client.SubscribeNewHead(context.Background(), heads) 580 if err != nil { 581 log.Crit("Failed to subscribe to head events", "err", err) 582 } 583 defer sub.Unsubscribe() 584 585 // Start a goroutine to update the state from head notifications in the background 586 update := make(chan *types.Header) 587 588 go func() { 589 for head := range update { 590 // New chain head arrived, query the current stats and stream to clients 591 timestamp := time.Unix(int64(head.Time), 0) 592 if time.Since(timestamp) > time.Hour { 593 log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp)) 594 continue 595 } 596 if err := f.refresh(head); err != nil { 597 log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err) 598 continue 599 } 600 // Faucet state retrieved, update locally and send to clients 601 f.lock.RLock() 602 log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price) 603 604 balance := new(big.Int).Div(f.balance, btper) 605 peers := f.stack.Server().PeerCount() 606 607 for _, conn := range f.conns { 608 if err := send(conn, map[string]interface{}{ 609 "funds": balance, 610 "funded": f.nonce, 611 "peers": peers, 612 "requests": f.reqs, 613 }, time.Second); err != nil { 614 log.Warn("Failed to send stats to client", "err", err) 615 conn.Close() 616 continue 617 } 618 if err := send(conn, head, time.Second); err != nil { 619 log.Warn("Failed to send header to client", "err", err) 620 conn.Close() 621 } 622 } 623 f.lock.RUnlock() 624 } 625 }() 626 // Wait for various events and assing to the appropriate background threads 627 for { 628 select { 629 case head := <-heads: 630 // New head arrived, send if for state update if there's none running 631 select { 632 case update <- head: 633 default: 634 } 635 636 case <-f.update: 637 // Pending requests updated, stream to clients 638 f.lock.RLock() 639 for _, conn := range f.conns { 640 if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil { 641 log.Warn("Failed to send requests to client", "err", err) 642 conn.Close() 643 } 644 } 645 f.lock.RUnlock() 646 } 647 } 648 } 649 650 // sends transmits a data packet to the remote end of the websocket, but also 651 // setting a write deadline to prevent waiting forever on the node. 652 func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error { 653 if timeout == 0 { 654 timeout = 60 * time.Second 655 } 656 conn.SetWriteDeadline(time.Now().Add(timeout)) 657 return websocket.JSON.Send(conn, value) 658 } 659 660 // sendError transmits an error to the remote end of the websocket, also setting 661 // the write deadline to 1 second to prevent waiting forever. 662 func sendError(conn *websocket.Conn, err error) error { 663 return send(conn, map[string]string{"error": err.Error()}, time.Second) 664 } 665 666 // sendSuccess transmits a success message to the remote end of the websocket, also 667 // setting the write deadline to 1 second to prevent waiting forever. 668 func sendSuccess(conn *websocket.Conn, msg string) error { 669 return send(conn, map[string]string{"success": msg}, time.Second) 670 } 671 672 // authTwitter tries to authenticate a faucet request using Twitter posts, returning 673 // the username, avatar URL and btpereum address to fund on success. 674 func authTwitter(url string) (string, string, common.Address, error) { 675 // Ensure the user specified a meaningful URL, no fancy nonsense 676 parts := strings.Split(url, "/") 677 if len(parts) < 4 || parts[len(parts)-2] != "status" { 678 return "", "", common.Address{}, errors.New("Invalid Twitter status URL") 679 } 680 // Twitter's API isn't really friendly with direct links. Still, we don't 681 // want to do ask read permissions from users, so just load the public posts and 682 // scrape it for the btpereum address and profile URL. 683 res, err := http.Get(url) 684 if err != nil { 685 return "", "", common.Address{}, err 686 } 687 defer res.Body.Close() 688 689 // Resolve the username from the final redirect, no intermediate junk 690 parts = strings.Split(res.Request.URL.String(), "/") 691 if len(parts) < 4 || parts[len(parts)-2] != "status" { 692 return "", "", common.Address{}, errors.New("Invalid Twitter status URL") 693 } 694 username := parts[len(parts)-3] 695 696 body, err := ioutil.ReadAll(res.Body) 697 if err != nil { 698 return "", "", common.Address{}, err 699 } 700 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 701 if address == (common.Address{}) { 702 return "", "", common.Address{}, errors.New("No btpereum address found to fund") 703 } 704 var avatar string 705 if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 706 avatar = parts[1] 707 } 708 return username + "@twitter", avatar, address, nil 709 } 710 711 // authFacebook tries to authenticate a faucet request using Facebook posts, 712 // returning the username, avatar URL and btpereum address to fund on success. 713 func authFacebook(url string) (string, string, common.Address, error) { 714 // Ensure the user specified a meaningful URL, no fancy nonsense 715 parts := strings.Split(url, "/") 716 if len(parts) < 4 || parts[len(parts)-2] != "posts" { 717 return "", "", common.Address{}, errors.New("Invalid Facebook post URL") 718 } 719 username := parts[len(parts)-3] 720 721 // Facebook's Graph API isn't really friendly with direct links. Still, we don't 722 // want to do ask read permissions from users, so just load the public posts and 723 // scrape it for the btpereum address and profile URL. 724 res, err := http.Get(url) 725 if err != nil { 726 return "", "", common.Address{}, err 727 } 728 defer res.Body.Close() 729 730 body, err := ioutil.ReadAll(res.Body) 731 if err != nil { 732 return "", "", common.Address{}, err 733 } 734 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 735 if address == (common.Address{}) { 736 return "", "", common.Address{}, errors.New("No btpereum address found to fund") 737 } 738 var avatar string 739 if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 740 avatar = parts[1] 741 } 742 return username + "@facebook", avatar, address, nil 743 } 744 745 // authNoAuth tries to interpret a faucet request as a plain btpereum address, 746 // without actually performing any remote authentication. This mode is prone to 747 // Byzantine attack, so only ever use for truly private networks. 748 func authNoAuth(url string) (string, string, common.Address, error) { 749 address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url)) 750 if address == (common.Address{}) { 751 return "", "", common.Address{}, errors.New("No btpereum address found to fund") 752 } 753 return address.Hex() + "@noauth", "", address, nil 754 }