Skip to content
Snippets Groups Projects
Select Git revision
  • 9beef65a1a258290cd17e6a1e017979315f5fe9b
  • main default protected
2 results

cours_25.md

Blame
  • process-connection.go 5.07 KiB
    package ProcessConnection
    
    import (
    	"encoding/json"
    	"fmt"
    	"net"
    	ObjectStorageAPI "node/object-storage"
    	Sender "node/sender"
    	. "node/types"
    	"node/utilities"
    	"os"
    	"strings"
    	"sync"
    )
    
    func listAllTransactionsToClient(conn net.Conn) {
    	mess := Message{
    		MessageType: "list",
    		MessageBody: DB,
    	}
    
    	fmt.Println("Sending message to neighbour", mess)
    	encoder := json.NewEncoder(conn)
    	err := encoder.Encode(mess)
    	if err != nil {
    		fmt.Println("Error while encoding the transaction", err)
    		os.Exit(1)
    	}
    	conn.Close()
    }
    
    func processTransaction(serverListener net.Listener, serverConfig Config, objectStorage Blob, mess Message, amIRoot bool) {
    	var trans Transaction
    	var body map[string]interface{} = mess.MessageBody.(map[string]interface{})
    
    	// Convert mess to transaction
    	fmt.Println("Processing transaction")
    	trans.Id = body["id"].(string)
    	trans.Receiver = body["receiver"].(string)
    	trans.Sender = body["sender"].(string)
    	trans.Amount = body["amount"].(string)
    	utilities.PrintTransaction(trans)
    
    	database := ObjectStorageAPI.ReadDatabaseFromBlobStorage(objectStorage)
    	fmt.Println("The database before adding the transaction is ")
    	utilities.PrintingDatabaseToConsole(database)
    
    	reach := false
    	count := 0
    
    	limit := len(serverConfig.Neighbours)
    	if amIRoot {
    		reach = true
    		database = ObjectStorageAPI.AddTransactionToBlobStorage(trans, database, objectStorage)
    		fmt.Println("The database after adding the transaction is ")
    		utilities.PrintingDatabaseToConsole(database)
    		go Sender.SendTransactionToAllNeighbours(serverConfig, trans)
    	}
    
    	for count < limit {
    		if count != 0 || reach {
    			fmt.Println("Count is ", count, " to ", limit)
    
    			connection, err := serverListener.Accept()
    			if err != nil {
    				fmt.Println("Error accepting: ", err.Error())
    				err = nil
    				continue
    			}
    			fmt.Println("*****************************************")
    			fmt.Println("Processing client request number ", count)
    			fmt.Println("The process-manage-connection is ", connection)
    			fmt.Println("The remote address is ", connection.RemoteAddr())
    			fmt.Println("The local address is ", connection.LocalAddr())
    			fmt.Println("*****************************************")
    
    			err = json.NewDecoder(connection).Decode(&trans)
    			if err != nil {
    				fmt.Println("Error while decoding the transaction", err)
    				err = nil
    				continue
    			}
    			fmt.Println("Received back a transaction")
    			utilities.PrintTransaction(trans)
    		}
    
    		count++ // received message
    		if !reach {
    			reach = true
    			addTransactionToDb(trans)
    			go sendTransactionToAllNeighbours(serverConfig, trans)
    		}
    	}
    	fmt.Println("***********************************")
    	fmt.Println("All transactions have been received")
    	fmt.Println("***********************************")
    }
    
    func processRate(serverListener net.Listener, serverConfig Config, mess Message, amIRoot bool) {
    	var trans Transaction
    	var body map[string]interface{} = mess.MessageBody.(map[string]interface{})
    	trans.Id = body["id"].(string)
    	trans.Receiver = body["receiver"].(string)
    	trans.Sender = body["sender"].(string)
    	trans.Amount = body["amount"].(string)
    	utilities.PrintTransaction(trans)
    
    	// todo change this for cloud
    	address := strings.Split(conn.RemoteAddr().String(), ":")[0]
    	vote(server, trans, serverConfig, address, amIRoot)
    }
    
    func processFake(serverListener net.Listener, serverConfig Config, mess Message, amIRoot bool) {
    	var fakeTransaction Transaction
    	var body map[string]interface{} = mess.MessageBody.(map[string]interface{})
    	fakeTransaction.Id = body["id"].(string)
    	fakeTransaction.Receiver = body["receiver"].(string)
    	fakeTransaction.Sender = body["sender"].(string)
    	fakeTransaction.Amount = body["amount"].(string)
    	for transactionIndex := range DB {
    		if DB[transactionIndex].Id == fakeTransaction.Id {
    			DB[transactionIndex].Sender = fakeTransaction.Sender
    			DB[transactionIndex].Receiver = fakeTransaction.Receiver
    			DB[transactionIndex].Amount = fakeTransaction.Amount
    			fmt.Println("Successfully replaced the legitimate transaction with a fake one!")
    		}
    	}
    }
    
    func ProcessClient(conn net.Conn, server net.Listener, objectStorage Blob, serverConfig Config, amIRoot bool, mutex *sync.Mutex) {
    	mutex.Lock()
    	defer mutex.Unlock()
    	fmt.Println("Processing client")
    	fmt.Println("The conn is ", conn)
    	fmt.Println("The remote address is ", conn.RemoteAddr())
    	fmt.Println("The local address is ", conn.LocalAddr())
    
    	var mess Message
    	jsonDecoder := json.NewDecoder(conn)
    	err := jsonDecoder.Decode(&mess)
    	if err != nil || mess.MessageType == "error" {
    		fmt.Println("Error while decoding the message", err)
    		return
    	}
    
    	fmt.Println("The message is ", mess)
    	if mess.MessageType == "transaction" {
    		fmt.Println("Received a transaction.. processing")
    		processTransaction(server, serverConfig, objectStorage, mess, amIRoot)
    	} else if mess.MessageType == "rate" {
    		fmt.Println("Received a rate")
    		processRate()
    	} else if mess.MessageType == "fake" {
    		fmt.Println("Received a fake transaction")
    		processFake()
    	} else if mess.MessageType == "list" {
    		fmt.Println("Received an order to list all transactions")
    		listAllTransactionsToClient(conn)
    	} else {
    		fmt.Println("Unknown message type")
    	}
    }