Esempio n. 1
0
File: node.go Progetto: jaked122/Sia
// clientHandler reads data sent by a client and processes it.
func (tcp *TCPServer) clientHandler(conn net.Conn) {
	// read first 1024 bytes
	buffer := make([]byte, 1024)

	// read first 1024 bytes
	b, err := conn.Read(buffer)
	if err != nil {
		return
	}

	// split message into payload length, identifier, and payload
	payloadLength, _ := binary.Uvarint(buffer[:4])
	id := common.Identifier(buffer[4])
	payload := buffer[5:b]

	// read rest of payload, 1024 bytes at a time
	// TODO: add a timeout
	bytesRead := len(payload)
	for uint64(bytesRead) != payloadLength {
		b, err = conn.Read(buffer)
		if err != nil {
			return
		}
		payload = append(payload, buffer[:b]...)
		bytesRead += b
	}

	// look up message handler and call it
	handler, exists := tcp.MessageHandlers[id]
	if exists {
		handler.HandleMessage(payload)
	}
	// todo: decide on behavior when encountering uninitialized Identifier
}
Esempio n. 2
0
// Create and initialize a state object
func CreateState(messageSender common.MessageSender, participantIndex participantIndex) (s State, err error) {
	// check that we have a non-nil messageSender
	if messageSender == nil {
		err = fmt.Errorf("Cannot initialize with a nil messageSender")
		return
	}

	// check that participantIndex is legal
	if int(participantIndex) >= common.QuorumSize {
		err = fmt.Errorf("Invalid participant index!")
		return
	}

	// initialize crypto keys
	pubKey, secKey, err := crypto.CreateKeyPair()
	if err != nil {
		return
	}

	// create and fill out the participant object
	self := new(Participant)
	self.Address = messageSender.Address()
	self.Address.Id = common.Identifier(participantIndex)
	self.PublicKey = pubKey

	// calculate the value of an empty hash (default for storedEntropyStage2 on all hosts is a blank array)
	emptyHash, err := crypto.CalculateTruncatedHash(s.storedEntropyStage2[:])
	if err != nil {
		return
	}

	// set state variables to their defaults
	s.messageSender = messageSender
	s.AddParticipant(self, participantIndex)
	s.secretKey = secKey
	for i := range s.previousEntropyStage1 {
		s.previousEntropyStage1[i] = emptyHash
	}
	s.participantIndex = participantIndex
	s.currentStep = 1
	s.wallets = make(map[string]uint64)

	return
}
Esempio n. 3
0
File: node.go Progetto: Radzell/Sia
// AddMessageHandler adds a MessageHandler to the MessageHandlers slice.
// It creates an identifier associated with that MessageHandler, and returns
// an Address incorporating the identifier.
func (tcp *TCPServer) AddMessageHandler(mh common.MessageHandler) common.Address {
	tcp.MessageHandlers = append(tcp.MessageHandlers, mh)
	addr := tcp.Addr
	addr.Id = common.Identifier(len(tcp.MessageHandlers) - 1)
	return addr
}