Example #1
0
func NewRouter(key *utils.PrivateKey, logger *log.Logger, config utils.Config) (*Router, error) {
	exit := make(chan int)
	listener, err := getOpenPortConn(config)
	if err != nil {
		return nil, err
	}

	logger.Info("Node ID: %s", key.Digest().String())
	logger.Info("Node Socket: %v", listener.Addr())

	ns := utils.GlobalNamespace
	id := utils.NewNodeID(ns, key.Digest())

	r := Router{
		id:       id,
		listener: listener,
		key:      key,
		sessions: make(map[utils.NodeID]*session),
		mainDht:  dht.NewDHT(10, id, id, listener.RawConn, logger),
		groupDht: make(map[utils.NodeID]*dht.DHT),

		receivedPackets: make(map[[20]byte]int),

		logger: logger,
		recv:   make(chan Message, 100),
		send:   make(chan internal.Packet, 100),
		exit:   exit,
	}

	go r.run()
	return &r, nil
}
Example #2
0
func getKey(keyfile string) (*utils.PrivateKey, error) {
	_, err := os.Stat(filepath.Dir(keyfile))

	if _, err := os.Stat(keyfile); err != nil {
		err := os.MkdirAll(filepath.Dir(keyfile), 0755)
		if err != nil {
			return nil, err
		}
		key := utils.GeneratePrivateKey()
		pem, err := key.MarshalText()
		err = ioutil.WriteFile(keyfile, pem, 0644)
		if err != nil {
			return nil, err
		}
		fmt.Printf(" -> Create a new private key: %s\n", keyfile)
	}

	pem, err := ioutil.ReadFile(keyfile)
	if err != nil {
		return nil, err
	}

	var key utils.PrivateKey
	err = key.UnmarshalText(pem)
	if err != nil {
		return nil, err
	}
	return &key, nil
}
Example #3
0
func (p *Packet) Sign(key *utils.PrivateKey) error {
	sign := key.Sign(p.Serialize())
	if sign == nil {
		return errors.New("cannot sign packet")
	}
	p.S = *sign
	return nil
}
Example #4
0
// NewClient generates a Client with the given PrivateKey.
func NewClient(key *utils.PrivateKey, config utils.Config) (*Client, error) {
	logger := log.NewLogger()

	r, err := router.NewRouter(key, logger, config)
	if err != nil {
		return nil, err
	}

	c := &Client{
		router: r,
		readch: make(chan router.Message),
		mbuf:   newMessageBuffer(128),
		id:     utils.NewNodeID(utils.GlobalNamespace, key.Digest()),
		config: config,
		Logger: logger,
	}

	return c, nil
}