beacon chain package

pull/126/head
ak 6 years ago
parent 27c5f86ee1
commit 2ef8e00026
  1. 109
      beaconchain/beaconchain.go
  2. 36
      beaconchain/beaconchain_handler.go
  3. 23
      beaconchain/beaconchain_test.go

@ -1,17 +1,18 @@
package beaconchain package beaconchain
import ( import (
"fmt" "math/rand"
"net" "net"
"os" "os"
"sync" "sync"
"github.com/dedis/kyber" "github.com/dedis/kyber"
"github.com/harmony-one/harmony/bcconn"
"github.com/harmony-one/harmony/crypto/pki" "github.com/harmony-one/harmony/crypto/pki"
"github.com/harmony-one/harmony/log" "github.com/harmony-one/harmony/log"
"github.com/harmony-one/harmony/node"
"github.com/harmony-one/harmony/p2p" "github.com/harmony-one/harmony/p2p"
proto_identity "github.com/harmony-one/harmony/proto/identity" proto_identity "github.com/harmony-one/harmony/proto/identity"
"github.com/harmony-one/harmony/utils"
) )
var mutex sync.Mutex var mutex sync.Mutex
@ -19,83 +20,79 @@ var identityPerBlock = 100000
// BeaconChain (Blockchain) keeps Identities per epoch, currently centralized! // BeaconChain (Blockchain) keeps Identities per epoch, currently centralized!
type BeaconChain struct { type BeaconChain struct {
//Identities []*IdentityBlock //No need to have the identity block as of now Leaders []*bcconn.NodeInfo
Identities []*node.Node log log.Logger
log log.Logger ShardLeaderMap map[int]*bcconn.NodeInfo
PeerToShardMap map[*node.Node]int PubKey kyber.Point
ShardLeaderMap map[int]*node.Node NumberOfShards int
PubKey kyber.Point NumberOfNodesAdded int
NumberOfShards int IP string
NumberOfLeadersAdded int Port string
} }
// New return BeaconChain. //Init
func New(filename string) *BeaconChain { func New(numShards int, ip, port string) *BeaconChain {
idc := BeaconChain{} bc := BeaconChain{}
//idc.NumberOfShards = readConfigFile(filename) bc.log = log.New()
idc.log = log.New() bc.NumberOfShards = numShards
idc.NumberOfShards = 2 bc.PubKey = generateIDCKeys()
idc.PubKey = generateIDCKeys() bc.NumberOfNodesAdded = 0
return &idc bc.Port = port
} bc.IP = ip
return &bc
func readConfigFile(filename string) int {
return 2
} }
func generateIDCKeys() kyber.Point { func generateIDCKeys() kyber.Point {
priKey := pki.GetPrivateKeyFromInt(10) r := rand.Intn(1000)
priKey := pki.GetPrivateKeyFromInt(r)
pubkey := pki.GetPublicKeyFromPrivateKey(priKey) pubkey := pki.GetPublicKeyFromPrivateKey(priKey)
return pubkey return pubkey
} }
// AcceptConnections welcomes new connections //AcceptConnections welcomes new connections
func (IDC *BeaconChain) AcceptConnections(b []byte) { func (bc *BeaconChain) AcceptConnections(b []byte) {
NewNode := node.DeserializeNode(b) Node := bcconn.DeserializeNodeInfo(b)
fmt.Println(NewNode) bc.log.Info("Obtained node information, updating local information")
} bc.NumberOfNodesAdded = bc.NumberOfNodesAdded + 1
_, isLeader := utils.AllocateShard(bc.NumberOfNodesAdded, bc.NumberOfShards)
if isLeader {
bc.Leaders = append(bc.Leaders, Node)
}
/**
func (IDC *BeaconChain) registerNode(Node *node.Node) { **IMPORTANT**
IDC.Identities = append(IDC.Identities, Node)
fmt.Println(IDC.Identities)
//IDC.CommunicatePublicKeyToNode(Node.SelfPeer)
return
}
// CommunicatePublicKeyToNode communicates public key to node. Note that public key is not in kyber.Scalar form it is in byte form.
func (IDC *BeaconChain) CommunicatePublicKeyToNode(peer p2p.Peer) { Use following conversion to get back the actual key
pbkey := pki.GetBytesFromPublicKey(IDC.PubKey) //peer.PubKey = crypto.Ed25519Curve.Point()
msgToSend := proto_identity.ConstructIdentityMessage(proto_identity.Acknowledge, pbkey[:]) //err = peer.PubKey.UnmarshalBinary(p.PubKey[:])
p2p.SendMessage(peer, msgToSend)
}
//StartServer a server and process the request by a handler. **/
func (IDC *BeaconChain) StartServer() { response := bcconn.ResponseRandomNumber{NumberOfShards: bc.NumberOfShards, NumberOfNodesAdded: bc.NumberOfNodesAdded, Leaders: bc.Leaders}
IDC.log.Info("Starting IDC server...") //log.Info does nothing for me! (ak) msg := bcconn.SerializeRandomInfo(response)
IDC.listenOnPort() msgToSend := proto_identity.ConstructIdentityMessage(proto_identity.Acknowledge, msg)
p2p.SendMessage(Node.Self, msgToSend)
} }
func (IDC *BeaconChain) listenOnPort() { //StartServer a server and process the request by a handler.
addr := net.JoinHostPort("127.0.0.1", "8081") func (bc *BeaconChain) StartServer() {
bc.log.Info("Starting Beaconchain server ...")
ip := bc.IP
port := bc.Port
addr := net.JoinHostPort(ip, port)
listen, err := net.Listen("tcp", addr) listen, err := net.Listen("tcp", addr)
if err != nil { if err != nil {
IDC.log.Crit("Socket listen port failed") bc.log.Crit("Socket listen port failed")
os.Exit(1) os.Exit(1)
} else {
IDC.log.Info("Identity chain is now listening ..")
} }
defer listen.Close() defer listen.Close()
for { for {
IDC.log.Info("I am accepting connections now") bc.log.Info("beacon chain is now listening ..")
conn, err := listen.Accept() conn, err := listen.Accept()
fmt.Println(conn)
if err != nil { if err != nil {
IDC.log.Crit("Error listening on port. Exiting", "8081") bc.log.Crit("Error listening on port. Exiting", "8081")
continue continue
} else {
IDC.log.Info("I am accepting connections now")
} }
go IDC.BeaconChainHandler(conn) go bc.BeaconChainHandler(conn)
} }
} }

@ -1,9 +1,7 @@
package beaconchain package beaconchain
import ( import (
"fmt"
"net" "net"
"os"
"github.com/harmony-one/harmony/p2p" "github.com/harmony-one/harmony/p2p"
"github.com/harmony-one/harmony/proto" "github.com/harmony-one/harmony/proto"
@ -11,38 +9,31 @@ import (
) )
// BeaconChainHandler handles registration of new Identities // BeaconChainHandler handles registration of new Identities
// This could have been its seperate package like consensus, but am avoiding creating a lot of packages. func (bc *BeaconChain) BeaconChainHandler(conn net.Conn) {
func (IDC *BeaconChain) BeaconChainHandler(conn net.Conn) {
content, err := p2p.ReadMessageContent(conn) content, err := p2p.ReadMessageContent(conn)
if err != nil { if err != nil {
IDC.log.Error("Read p2p data failed") bc.log.Error("Read p2p data failed")
return return
} }
IDC.log.Info("received connection") bc.log.Info("received connection", "connectionIp", conn.RemoteAddr())
msgCategory, err := proto.GetMessageCategory(content) msgCategory, err := proto.GetMessageCategory(content)
if err != nil { if err != nil {
IDC.log.Error("Read message category failed", "err", err) bc.log.Error("Read message category failed", "err", err)
return return
} }
if msgCategory != proto.Identity {
IDC.log.Error("Identity Chain Recieved incorrect protocol message")
os.Exit(1)
} else {
fmt.Println("Message category is correct")
}
msgType, err := proto.GetMessageType(content) msgType, err := proto.GetMessageType(content)
if err != nil { if err != nil {
IDC.log.Error("Read action type failed") bc.log.Error("Read action type failed")
return return
} }
msgPayload, err := proto.GetMessagePayload(content) msgPayload, err := proto.GetMessagePayload(content)
if err != nil { if err != nil {
IDC.log.Error("Read message payload failed") bc.log.Error("Read message payload failed")
return return
} }
identityMsgPayload, err := proto_identity.GetIdentityMessagePayload(msgPayload) identityMsgPayload, err := proto_identity.GetIdentityMessagePayload(msgPayload)
if err != nil { if err != nil {
IDC.log.Error("Read message payload failed") bc.log.Error("Read message payload failed")
return return
} }
switch msgCategory { switch msgCategory {
@ -50,17 +41,20 @@ func (IDC *BeaconChain) BeaconChainHandler(conn net.Conn) {
actionType := proto_identity.IDMessageType(msgType) actionType := proto_identity.IDMessageType(msgType)
switch actionType { switch actionType {
case proto_identity.Identity: case proto_identity.Identity:
bc.log.Info("Message category is of the type identity protocol, which is correct!")
idMsgType, err := proto_identity.GetIdentityMessageType(msgPayload) idMsgType, err := proto_identity.GetIdentityMessageType(msgPayload)
if err != nil { if err != nil {
fmt.Println("Error finding the identity message type") bc.log.Error("Error finding the identity message type")
} }
switch idMsgType { switch idMsgType {
case proto_identity.Register: case proto_identity.Register:
IDC.AcceptConnections(identityMsgPayload) bc.log.Info("Identity Message Type is of the type Register")
case proto_identity.Acknowledge: bc.AcceptConnections(identityMsgPayload)
// IDC.acceptNewConnection(msgPayload) default:
panic("Unrecognized identity message type")
} }
default:
panic("Unrecognized message category")
} }
} }

@ -0,0 +1,23 @@
package beaconchain
import "testing"
func TestNewNode(t *testing.T) {
var ip, port string
ip = "127.0.0.1"
port = "8080"
numshards := 2
bc := New(numshards, ip, port)
if bc.PubKey == nil {
t.Error("beacon chain public key not initialized")
}
if bc.NumberOfNodesAdded != 0 {
t.Error("beacon chain number of nodes starting with is not zero! (should be zero)")
}
if bc.NumberOfShards != numshards {
t.Error("beacon chain number of shards not initialized to given number of desired shards")
}
}
Loading…
Cancel
Save