github.com/turingchain2020/turingchain@v1.1.21/cmd/miner_accounts/main.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package main 挖矿监控
     6  package main
     7  
     8  import (
     9  	"flag"
    10  	"fmt"
    11  	"io"
    12  	"net"
    13  	"net/http"
    14  	"net/rpc"
    15  	"net/rpc/jsonrpc"
    16  	"os"
    17  	"path/filepath"
    18  	"strings"
    19  
    20  	l "github.com/turingchain2020/turingchain/common/log/log15"
    21  	tml "github.com/BurntSushi/toml"
    22  	"github.com/rs/cors"
    23  
    24  	"github.com/turingchain2020/turingchain/cmd/miner_accounts/accounts"
    25  )
    26  
    27  var (
    28  	log        = l.New("module", "main")
    29  	configPath = flag.String("f", "miner_accounts.toml", "configfile")
    30  )
    31  
    32  //HTTPConn http连接
    33  type HTTPConn struct {
    34  	in  io.Reader
    35  	out io.Writer
    36  }
    37  
    38  func (c *HTTPConn) Read(p []byte) (n int, err error)  { return c.in.Read(p) }
    39  func (c *HTTPConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
    40  
    41  //Close 关闭连接
    42  func (c *HTTPConn) Close() error { return nil }
    43  
    44  func main() {
    45  	d, _ := os.Getwd()
    46  	log.Debug("current dir:", "dir", d)
    47  	os.Chdir(pwd())
    48  	d, _ = os.Getwd()
    49  	log.Debug("current dir:", "dir", d)
    50  	flag.Parse()
    51  	cfg := InitCfg(*configPath)
    52  	log.Debug("load config", "cfgPath", *configPath, "wl", cfg.Whitelist, "addr", cfg.JrpcBindAddr, "miners", cfg.MinerAddr)
    53  	whitelist := InitWhiteList(cfg)
    54  
    55  	listen, err := net.Listen("tcp", cfg.JrpcBindAddr)
    56  	if err != nil {
    57  		panic(err)
    58  	}
    59  
    60  	go accounts.SyncBlock(cfg.TuringchainHost)
    61  
    62  	shower := accounts.ShowMinerAccount{DataDir: cfg.DataDir, Addrs: cfg.MinerAddr}
    63  	server := rpc.NewServer()
    64  	server.Register(&shower)
    65  
    66  	var handler http.Handler = http.HandlerFunc(
    67  		func(w http.ResponseWriter, r *http.Request) {
    68  			//fmt.Println(r.URL, r.Header, r.Body)
    69  
    70  			if !checkWhitlist(strings.Split(r.RemoteAddr, ":")[0], whitelist) {
    71  				log.Error("HandlerFunc", "peer not whitelist", r.RemoteAddr)
    72  				w.Write([]byte(`{"errcode":"-1","result":null,"msg":"reject"}`))
    73  				return
    74  			}
    75  
    76  			if r.URL.Path == "/" {
    77  				serverCodec := jsonrpc.NewServerCodec(&HTTPConn{in: r.Body, out: w})
    78  				w.Header().Set("Content-type", "application/json")
    79  				w.WriteHeader(200)
    80  
    81  				err := server.ServeRequest(serverCodec)
    82  				if err != nil {
    83  					log.Debug("Error while serving JSON request: %v", err)
    84  					return
    85  				}
    86  			}
    87  		})
    88  
    89  	//co := cors.New(cors.Options{
    90  	//    AllowedOrigins: []string{"http://foo.com"},
    91  	//    Debug: true,
    92  	//})
    93  	co := cors.New(cors.Options{})
    94  	handler = co.Handler(handler)
    95  
    96  	http.Serve(listen, handler)
    97  
    98  	fmt.Println(handler)
    99  
   100  }
   101  
   102  //InitCfg 初始化cfg
   103  func InitCfg(path string) *accounts.Config {
   104  	var cfg accounts.Config
   105  	if _, err := tml.DecodeFile(path, &cfg); err != nil {
   106  		fmt.Println(err)
   107  		os.Exit(0)
   108  	}
   109  	fmt.Println(cfg)
   110  	return &cfg
   111  }
   112  
   113  //InitWhiteList 初始化白名单
   114  func InitWhiteList(cfg *accounts.Config) map[string]bool {
   115  	whitelist := map[string]bool{}
   116  	if len(cfg.Whitelist) == 1 && cfg.Whitelist[0] == "*" {
   117  		whitelist["0.0.0.0"] = true
   118  		return whitelist
   119  	}
   120  
   121  	for _, addr := range cfg.Whitelist {
   122  		log.Debug("initWhitelist", "addr", addr)
   123  		whitelist[addr] = true
   124  	}
   125  	return whitelist
   126  }
   127  
   128  func pwd() string {
   129  	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
   130  	if err != nil {
   131  		panic(err)
   132  	}
   133  	return dir
   134  }
   135  
   136  func checkWhitlist(addr string, whitlist map[string]bool) bool {
   137  	if _, ok := whitlist["0.0.0.0"]; ok {
   138  		return true
   139  	}
   140  
   141  	if _, ok := whitlist[addr]; ok {
   142  		return true
   143  	}
   144  	return false
   145  }