fixed typos errors added first waitnode test

pull/61/head
Alok Kothari 6 years ago
parent d3060ee20a
commit 9611867b87
  1. 11
      identitychain/identityblock.go
  2. 86
      identitychain/identitychain.go
  3. 26
      waitnode/waitNode.go
  4. 9
      waitnode/waitNode_test.go

@ -44,26 +44,25 @@ func DeserializeBlock(d []byte) *IdentityBlock {
// NewBlock creates and returns a new block. // NewBlock creates and returns a new block.
func NewBlock(Identities []*waitnode.WaitNode, prevBlockHash [32]byte) *IdentityBlock { func NewBlock(Identities []*waitnode.WaitNode, prevBlockHash [32]byte) *IdentityBlock {
block := &IdentityBlock{Timestamp: time.Now().Unix(), PrevBlockHash: prevBlockHash, NumIdentities: int32(len(Identities)), Identities: Identities} block := &IdentityBlock{Timestamp: time.Now().Unix(), PrevBlockHash: prevBlockHash, NumIdentities: int32(len(Identities)), Identities: Identities}
return &block return block
} }
// CalculateBlockHash returns a hash of the block // CalculateBlockHash returns a hash of the block
func (b *IdentityBlock) CalculateBlockHash() []byte { func (b *IdentityBlock) CalculateBlockHash() [32]byte {
var hashes [][]byte var hashes [][]byte
var blockHash [32]byte var blockHash [32]byte
hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(b.Timestamp)) hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(b.Timestamp))
hashes = append(hashes, b.PrevBlockHash[:]) hashes = append(hashes, b.PrevBlockHash[:])
for _, id := range b.Identities { for _, id := range b.Identities {
hashes = append(hashes, id) hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(id.ID))
} }
hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(b.NumIdentities) hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(b.NumIdentities))
blockHash = sha256.Sum256(bytes.Join(hashes, []byte{})) blockHash = sha256.Sum256(bytes.Join(hashes, []byte{}))
return blockHash[:] return blockHash
} }
// NewGenesisBlock creates and returns genesis Block. // NewGenesisBlock creates and returns genesis Block.
func NewGenesisBlock() *IdentityBlock { func NewGenesisBlock() *IdentityBlock {
numTxs := 0
var Ids []*waitnode.WaitNode var Ids []*waitnode.WaitNode
block := &IdentityBlock{Timestamp: time.Now().Unix(), PrevBlockHash: [32]byte{}, NumIdentities: 1, Identities: Ids} block := &IdentityBlock{Timestamp: time.Now().Unix(), PrevBlockHash: [32]byte{}, NumIdentities: 1, Identities: Ids}
return block return block

@ -1,6 +1,7 @@
package identitychain package identitychain
import ( import (
"fmt"
"net" "net"
"os" "os"
"sync" "sync"
@ -8,17 +9,17 @@ import (
"github.com/simple-rules/harmony-benchmark/log" "github.com/simple-rules/harmony-benchmark/log"
"github.com/simple-rules/harmony-benchmark/p2p" "github.com/simple-rules/harmony-benchmark/p2p"
"github.com/simple-rules/harmony-benchmark/waitnode" "github.com/simple-rules/harmony-benchmark/waitnode"
"github.com/simple-rules/harmony-benchmark/proto"
) )
var mutex sync.Mutex var mutex sync.Mutex
var IdentityPerBlock := 100000 var IdentityPerBlock = 100000
// IdentityChain (Blockchain) keeps Identities per epoch, currently centralized! // IdentityChain (Blockchain) keeps Identities per epoch, currently centralized!
type IdentityChain struct { type IdentityChain struct {
Identities []*IdentityBlock Identities []*IdentityBlock
PendingIdentities []*waitnode.WaitNode PendingIdentities []*waitnode.WaitNode
log log.Logger log log.Logger
Peer p2p.Peer Peer p2p.Peer
} }
//IdentityChainHandler handles registration of new Identities //IdentityChainHandler handles registration of new Identities
@ -26,29 +27,30 @@ func (IDC *IdentityChain) IdentityChainHandler(conn net.Conn) {
// Read p2p message payload // Read p2p message payload
content, err := p2p.ReadMessageContent(conn) content, err := p2p.ReadMessageContent(conn)
if err != nil { if err != nil {
IDC.log.Error("Read p2p data failed", "err", err, "node", node) IDC.log.Error("Read p2p data failed")
return return
} }
fmt.Printf("content is %b", content)
msgCategory, err := proto.GetMessageCategory(content) // msgCategory, err := proto.GetMessageCategory(content)
if err != nil { // if err != nil {
IDC.log.Error("Read node type failed", "err", err, "node", node) // IDC.log.Error("Read node type failed", "err", err, "node", node)
return // return
} // }
msgType, err := proto.GetMessageType(content) // msgType, err := proto.GetMessageType(content)
if err != nil { // if err != nil {
IDC.log.Error("Read action type failed", "err", err, "node", node) // IDC.log.Error("Read action type failed", "err", err, "node", node)
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", "err", err, "node", node) // IDC.log.Error("Read message payload failed", "err", err, "node", node)
return // return
} // }
NewWaitNode := *waitnode.DeserializeWaitNode(msgPayload) // NewWaitNode := *waitnode.DeserializeWaitNode(msgPayload)
IDC.PendingIdentities = append(IDC.PendingIdentities, NewWaitNode) // IDC.PendingIdentities = append(IDC.PendingIdentities, NewWaitNode)
} }
// GetLatestBlock gests the latest block at the end of the chain // GetLatestBlock gests the latest block at the end of the chain
@ -59,37 +61,40 @@ func (IDC *IdentityChain) GetLatestBlock() *IdentityBlock {
return IDC.Identities[len(IDC.Identities)-1] return IDC.Identities[len(IDC.Identities)-1]
} }
//CreateNewBlock is to create the Blocks to be added to the chain //UpdateIdentityChain is to create the Blocks to be added to the chain
func (IDC *IdentityChain) MakeNewBlock() *IdentityBlock { func (IDC *IdentityChain) UpdateIdentityChain() {
if len(IDC.Identities) == 0 {
return NewGenesisBlock()
}
//If there are no more Identities registring the blockchain is dead //If there are no more Identities registring the blockchain is dead
if len(IDC.PendingIdentities) == 0 { if len(IDC.PendingIdentities) == 0 {
// This is abd, because previous block might not be alive // This is abd, because previous block might not be alive
return IDC.GetLatestBlock() return
} }
prevBlock := IDC.GetLatestBlock() if len(IDC.Identities) == 0 {
NewIdentities := IDC.PendingIdentities[:IdentityPerBlock] block := NewGenesisBlock()
IDC.PendingIdentities = IDC.PendingIdentities[IdentityPerBlock]: IDC.Identities = append(IDC.Identities, block)
//All other blocks are dropped. } else {
IDBlock = NewBlock(NewIdentities,prevBlock.CalculateBlockHash()) prevBlock := IDC.GetLatestBlock()
IDC.Identities = append(IDBlock,IDC.Identities) prevBlockHash := prevBlock.CalculateBlockHash()
NewIdentities := IDC.PendingIdentities[:IdentityPerBlock]
IDC.PendingIdentities = IDC.PendingIdentities[IdentityPerBlock:]
//All other blocks are dropped.
IDBlock := NewBlock(NewIdentities, prevBlockHash)
IDC.Identities = append(IDC.Identities, IDBlock)
} }
} }
func (IDC *IdentityChain) listenOnPort() { func (IDC *IdentityChain) listenOnPort() {
listen, err := net.Listen("tcp4", IDC.Peer.Ip + ":" IDC.Peer.Port) listen, err := net.Listen("tcp4", IDC.Peer.Ip+":"+IDC.Peer.Port)
defer listen.Close() defer listen.Close()
if err != nil { if err != nil {
IDC.log.Crit("Socket listen port failed", "port", port, "err", err) IDC.log.Crit("Socket listen port failed", "port", IDC.Peer.Port, "err", err)
os.Exit(1) os.Exit(1)
} }
for { for {
conn, err := listen.Accept() conn, err := listen.Accept()
if err != nil { if err != nil {
IDC.log.Crit("Error listening on port. Exiting.", "port", port) IDC.log.Crit("Error listening on port. Exiting.", "port", IDC.Peer.Port)
continue continue
} }
go IDC.IdentityChainHandler(conn) go IDC.IdentityChainHandler(conn)
@ -97,12 +102,5 @@ func (IDC *IdentityChain) listenOnPort() {
} }
func main() { func main() {
var IDC IdentityChain fmt.Print("Hi")
var nullPeer p2p.Peer
go func() {
genesisBlock := &IdentityBlock{nullPeer, 0}
mutex.Lock()
IDC.Identities = append(IDC.Identities, genesisBlock)
mutex.Unlock()
}()
} }

@ -4,8 +4,8 @@ import (
"bytes" "bytes"
"crypto/sha256" "crypto/sha256"
"encoding/gob" "encoding/gob"
"log"
"github.com/simple-rules/harmony-benchmark/log"
"github.com/simple-rules/harmony-benchmark/p2p" "github.com/simple-rules/harmony-benchmark/p2p"
"github.com/simple-rules/harmony-benchmark/proto/identity" "github.com/simple-rules/harmony-benchmark/proto/identity"
"github.com/simple-rules/harmony-benchmark/utils" "github.com/simple-rules/harmony-benchmark/utils"
@ -14,20 +14,19 @@ import (
//WaitNode is for nodes waiting to join consensus //WaitNode is for nodes waiting to join consensus
type WaitNode struct { type WaitNode struct {
Peer p2p.Peer Peer p2p.Peer
Log log.Logger ID uint16
ID []byte
} }
// StartServer a server and process the request by a handler. // StartServer a server and process the request by a handler.
func (node *WaitNode) StartServer() { func (node *WaitNode) StartServer() {
node.Log.Debug("Starting waitnode on server %d", "node", node.Peer.Ip, "port", node.Peer.Port) log.Printf("Starting waitnode on server %s and port %s", node.Peer.Ip, node.Peer.Port)
} }
func (node *WaitNode) connectIdentityChain(peer p2p.Peer) { func (node *WaitNode) connectIdentityChain(peer p2p.Peer) {
// replace by p2p peer
p2p.SendMessage(peer, identity.ConstructIdentityMessage(identity.REGISTER, node.SerializeWaitNode())) p2p.SendMessage(peer, identity.ConstructIdentityMessage(identity.REGISTER, node.SerializeWaitNode()))
} }
//Constructs node-id by hashing the IP.
func calculateHash(num string) []byte { func calculateHash(num string) []byte {
var hashes [][]byte var hashes [][]byte
hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(num)) hashes = append(hashes, utils.ConvertFixedDataIntoByteArray(num))
@ -35,33 +34,32 @@ func calculateHash(num string) []byte {
return hash[:] return hash[:]
} }
// Serialize serializes the block //SerializeWaitNode serializes the node
func (node *WaitNode) SerializeWaitNode() []byte { func (node *WaitNode) SerializeWaitNode() []byte {
var result bytes.Buffer var result bytes.Buffer
encoder := gob.NewEncoder(&result) encoder := gob.NewEncoder(&result)
err := encoder.Encode(node) err := encoder.Encode(node)
if err != nil { if err != nil {
log.Panic(err) log.Panic(err.Error())
} }
return result.Bytes() return result.Bytes()
} }
// DeserializeBlock deserializes a block // DeserializeWaitNode deserializes the node
func DeserializeWaitNode(d []byte) *WaitNode { func DeserializeWaitNode(d []byte) *WaitNode {
var block WaitNode var wn WaitNode
decoder := gob.NewDecoder(bytes.NewReader(d)) decoder := gob.NewDecoder(bytes.NewReader(d))
err := decoder.Decode(&WaitNode) err := decoder.Decode(&wn)
if err != nil { if err != nil {
log.Panic(err) log.Panic(err)
} }
return &WaitNode return &wn
} }
// New Create a new Node // New Create a new Node
func New(Peer p2p.Peer) *WaitNode { func New(Peer p2p.Peer) *WaitNode {
node := WaitNode{} node := WaitNode{}
node.Peer = Peer node.Peer = Peer
node.ID = calculateHash(Peer.Ip) node.ID = utils.GetUniqueIdFromPeer(Peer)
node.Log = log.New()
return &node return &node
} }

@ -2,8 +2,17 @@ package waitnode
import ( import (
"testing" "testing"
"github.com/simple-rules/harmony-benchmark/p2p"
) )
func TestNewNode(test *testing.T) { func TestNewNode(test *testing.T) {
p := p2p.Peer{Ip: "127.0.0.1", Port: "8080"}
wn := New(p)
b := wn.SerializeWaitNode()
wnd := DeserializeWaitNode(b)
if *wn != *wnd {
test.Error("Serialization is not working")
}
} }

Loading…
Cancel
Save