fix comments and fix ALL_CAPS lint

pull/75/head
Minh Doan 6 years ago
parent 9270730f76
commit bae896c944
  1. 4
      attack/attack.go
  2. 10
      client/client.go
  3. 4
      consensus/consensus.go
  4. 68
      consensus/consensus_leader.go
  5. 6
      consensus/consensus_leader_msg.go
  6. 38
      consensus/consensus_state.go
  7. 4
      consensus/consensus_test.go
  8. 64
      consensus/consensus_validator.go
  9. 5
      consensus/consensus_validator_msg.go
  10. 12
      node/node_handler.go
  11. 8
      proto/client/client.go
  12. 18
      proto/consensus/consensus.go
  13. 14
      proto/node/node.go
  14. 2
      send_txn.sh
  15. 4
      syncing/syncing.go

@ -101,8 +101,8 @@ func (attack *Attack) IncorrectResponse() bool {
return false
}
func (attack *Attack) UpdateConsensusReady(consensusId uint32) {
if consensusId > attack.ConsensusIdThreshold {
func (attack *Attack) UpdateConsensusReady(consensusID uint32) {
if consensusID > attack.ConsensusIdThreshold {
attack.readyByConsensusThreshold = true
}
}

@ -29,9 +29,9 @@ type Client struct {
func (client *Client) TransactionMessageHandler(msgPayload []byte) {
messageType := client_proto.TransactionMessageType(msgPayload[0])
switch messageType {
case client_proto.PROOF_OF_LOCK:
case client_proto.ProofOfLock:
// Decode the list of blockchain.CrossShardTxProof
txDecoder := gob.NewDecoder(bytes.NewReader(msgPayload[1:])) // skip the PROOF_OF_LOCK messge type
txDecoder := gob.NewDecoder(bytes.NewReader(msgPayload[1:])) // skip the ProofOfLock messge type
proofs := new([]blockchain.CrossShardTxProof)
err := txDecoder.Decode(proofs)
@ -39,11 +39,11 @@ func (client *Client) TransactionMessageHandler(msgPayload []byte) {
client.log.Error("Failed deserializing cross transaction proof list")
}
client.handleProofOfLockMessage(proofs)
case client_proto.UTXO_RESPONSE:
txDecoder := gob.NewDecoder(bytes.NewReader(msgPayload[1:])) // skip the PROOF_OF_LOCK messge type
case client_proto.UtxoResponse:
txDecoder := gob.NewDecoder(bytes.NewReader(msgPayload[1:])) // skip the ProofOfLock messge type
fetchUtxoResponse := new(client_proto.FetchUtxoResponseMessage)
err := txDecoder.Decode(fetchUtxoResponse)
client.log.Debug("UTXO_RESPONSE")
client.log.Debug("UtxoResponse")
if err != nil {
client.log.Error("Failed deserializing utxo response")

@ -50,7 +50,7 @@ type Consensus struct {
// Leader or validator Id - 2 byte
nodeId uint16
// Consensus Id (View Id) - 4 byte
consensusId uint32
consensusID uint32
// Blockhash - 32 byte
blockHash [32]byte
// BlockHeader to run consensus on
@ -141,7 +141,7 @@ func NewConsensus(ip, port, ShardID string, peers []p2p.Peer, leader p2p.Peer) *
// Set private key for myself so that I can sign messages.
consensus.priKey = crypto.Ed25519Curve.Scalar().SetInt64(int64(consensus.nodeId))
consensus.pubKey = pki.GetPublicKeyFromScalar(consensus.priKey)
consensus.consensusId = 0 // or view Id in the original pbft paper
consensus.consensusID = 0 // or view Id in the original pbft paper
myShardID, err := strconv.Atoi(ShardID)
if err != nil {

@ -23,7 +23,7 @@ var (
startTime time.Time
)
// Waits for the next new block to run consensus on
// WaitForNewBlock waits for the next new block to run consensus on
func (consensus *Consensus) WaitForNewBlock(blockChannel chan blockchain.Block) {
consensus.Log.Debug("Waiting for block", "consensus", consensus)
for { // keep waiting for new blocks
@ -39,7 +39,7 @@ func (consensus *Consensus) WaitForNewBlock(blockChannel chan blockchain.Block)
}
}
// Consensus message dispatcher for the leader
// ProcessMessageLeader dispatches consensus message for the leader.
func (consensus *Consensus) ProcessMessageLeader(message []byte) {
msgType, err := proto_consensus.GetConsensusMessageType(message)
if err != nil {
@ -52,29 +52,29 @@ func (consensus *Consensus) ProcessMessageLeader(message []byte) {
}
switch msgType {
case proto_consensus.START_CONSENSUS:
case proto_consensus.StartConsensus:
consensus.processStartConsensusMessage(payload)
case proto_consensus.COMMIT:
consensus.processCommitMessage(payload, CHALLENGE_DONE)
consensus.processCommitMessage(payload, ChallengeDone)
case proto_consensus.RESPONSE:
consensus.processResponseMessage(payload, COLLECTIVE_SIG_DONE)
case proto_consensus.FINAL_COMMIT:
consensus.processCommitMessage(payload, FINAL_CHALLENGE_DONE)
case proto_consensus.FINAL_RESPONSE:
consensus.processResponseMessage(payload, CollectiveSigDone)
case proto_consensus.FinalCommit:
consensus.processCommitMessage(payload, FinalChallengeDone)
case proto_consensus.FinalResponse:
consensus.processResponseMessage(payload, FINISHED)
default:
consensus.Log.Error("Unexpected message type", "msgType", msgType, "consensus", consensus)
}
}
// Handler for message which triggers consensus process
// processStartConsensusMessage is the handler for message which triggers consensus process.
func (consensus *Consensus) processStartConsensusMessage(payload []byte) {
// TODO: remove these method after testnet
tx := blockchain.NewCoinbaseTX([20]byte{0}, "y", 0)
consensus.startConsensus(blockchain.NewGenesisBlock(tx, 0))
}
// Starts a new consensus for a block by broadcast a announce message to the validators
// startConsensus starts a new consensus for a block by broadcast a announce message to the validators
func (consensus *Consensus) startConsensus(newBlock *blockchain.Block) {
// Copy over block hash and block header data
copy(consensus.blockHash[:], newBlock.Hash[:])
@ -89,16 +89,16 @@ func (consensus *Consensus) startConsensus(newBlock *blockchain.Block) {
consensus.Log.Debug("Stop encoding block")
msgToSend := consensus.constructAnnounceMessage()
p2p.BroadcastMessageFromLeader(consensus.GetValidatorPeers(), msgToSend)
// Set state to ANNOUNCE_DONE
consensus.state = ANNOUNCE_DONE
// Set state to AnnounceDone
consensus.state = AnnounceDone
consensus.commitByLeader(true)
}
// Leader commit to the message itself before receiving others commits
// commitByLeader commits to the message itself before receiving others commits
func (consensus *Consensus) commitByLeader(firstRound bool) {
// Generate leader's own commitment
secret, commitment := crypto.Commit(crypto.Ed25519Curve)
consensus.secret[consensus.consensusId] = secret
consensus.secret[consensus.consensusID] = secret
if firstRound {
(*consensus.commitments)[consensus.nodeId] = commitment
consensus.bitmap.SetKey(consensus.pubKey, true)
@ -108,12 +108,12 @@ func (consensus *Consensus) commitByLeader(firstRound bool) {
}
}
// Processes the commit message sent from validators
// processCommitMessage processes the commit message sent from validators
func (consensus *Consensus) processCommitMessage(payload []byte, targetState ConsensusState) {
// Read payload data
offset := 0
// 4 byte consensus id
consensusId := binary.BigEndian.Uint32(payload[offset : offset+4])
consensusID := binary.BigEndian.Uint32(payload[offset : offset+4])
offset += 4
// 32 byte block hash
@ -146,19 +146,19 @@ func (consensus *Consensus) processCommitMessage(payload []byte, targetState Con
// check consensus Id
consensus.mutex.Lock()
defer consensus.mutex.Unlock()
if consensusId != consensus.consensusId {
consensus.Log.Warn("Received COMMIT with wrong consensus Id", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
if consensusID != consensus.consensusID {
consensus.Log.Warn("Received COMMIT with wrong consensus Id", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
return
}
if bytes.Compare(blockHash, consensus.blockHash[:]) != 0 {
consensus.Log.Warn("Received COMMIT with wrong blockHash", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
consensus.Log.Warn("Received COMMIT with wrong blockHash", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
return
}
commitments := consensus.commitments // targetState == CHALLENGE_DONE
commitments := consensus.commitments // targetState == ChallengeDone
bitmap := consensus.bitmap
if targetState == FINAL_CHALLENGE_DONE {
if targetState == FinalChallengeDone {
commitments = consensus.finalCommitments
bitmap = consensus.finalBitmap
}
@ -186,8 +186,8 @@ func (consensus *Consensus) processCommitMessage(payload []byte, targetState Con
consensus.Log.Debug("Enough commitments received with signatures", "num", len(*commitments), "state", consensus.state)
// Broadcast challenge
msgTypeToSend := proto_consensus.CHALLENGE // targetState == CHALLENGE_DONE
if targetState == FINAL_CHALLENGE_DONE {
msgTypeToSend := proto_consensus.CHALLENGE // targetState == ChallengeDone
if targetState == FinalChallengeDone {
msgTypeToSend = proto_consensus.FINAL_CHALLENGE
}
msgToSend, challengeScalar, aggCommitment := consensus.constructChallengeMessage(msgTypeToSend)
@ -205,12 +205,12 @@ func (consensus *Consensus) processCommitMessage(payload []byte, targetState Con
}
// Add leader's response
consensus.responseByLeader(challengeScalar, targetState == CHALLENGE_DONE)
consensus.responseByLeader(challengeScalar, targetState == ChallengeDone)
// Broadcast challenge message
p2p.BroadcastMessageFromLeader(consensus.GetValidatorPeers(), msgToSend)
// Set state to targetState (CHALLENGE_DONE or FINAL_CHALLENGE_DONE)
// Set state to targetState (ChallengeDone or FinalChallengeDone)
consensus.state = targetState
}
}
@ -218,7 +218,7 @@ func (consensus *Consensus) processCommitMessage(payload []byte, targetState Con
// Leader commit to the message itself before receiving others commits
func (consensus *Consensus) responseByLeader(challenge kyber.Scalar, firstRound bool) {
// Generate leader's own commitment
response, err := crypto.Response(crypto.Ed25519Curve, consensus.priKey, consensus.secret[consensus.consensusId], challenge)
response, err := crypto.Response(crypto.Ed25519Curve, consensus.priKey, consensus.secret[consensus.consensusID], challenge)
if err == nil {
if firstRound {
(*consensus.responses)[consensus.nodeId] = response
@ -237,7 +237,7 @@ func (consensus *Consensus) processResponseMessage(payload []byte, targetState C
//#### Read payload data
offset := 0
// 4 byte consensus id
consensusId := binary.BigEndian.Uint32(payload[offset : offset+4])
consensusID := binary.BigEndian.Uint32(payload[offset : offset+4])
offset += 4
// 32 byte block hash
@ -262,13 +262,13 @@ func (consensus *Consensus) processResponseMessage(payload []byte, targetState C
defer consensus.mutex.Unlock()
// check consensus Id
if consensusId != consensus.consensusId {
if consensusID != consensus.consensusID {
shouldProcess = false
consensus.Log.Warn("Received RESPONSE with wrong consensus Id", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
consensus.Log.Warn("Received RESPONSE with wrong consensus Id", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
}
if bytes.Compare(blockHash, consensus.blockHash[:]) != 0 {
consensus.Log.Warn("Received RESPONSE with wrong blockHash", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
consensus.Log.Warn("Received RESPONSE with wrong blockHash", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
return
}
@ -283,7 +283,7 @@ func (consensus *Consensus) processResponseMessage(payload []byte, targetState C
return
}
commitments := consensus.commitments // targetState == COLLECTIVE_SIG_DONE
commitments := consensus.commitments // targetState == CollectiveSigDone
responses := consensus.responses
bitmap := consensus.bitmap
if targetState == FINISHED {
@ -352,7 +352,7 @@ func (consensus *Consensus) processResponseMessage(payload []byte, targetState C
copy(collectiveSig[:], collectiveSigAndBitmap[:64])
bitmap := collectiveSigAndBitmap[64:]
// Set state to COLLECTIVE_SIG_DONE or FINISHED
// Set state to CollectiveSigDone or FINISHED
consensus.state = targetState
if consensus.state != FINISHED {
@ -365,8 +365,8 @@ func (consensus *Consensus) processResponseMessage(payload []byte, targetState C
consensus.Log.Debug("Consensus reached with signatures.", "numOfSignatures", len(*responses))
// Reset state to FINISHED, and clear other data.
consensus.ResetState()
consensus.consensusId++
consensus.Log.Debug("HOORAY!!! CONSENSUS REACHED!!!", "consensusId", consensus.consensusId)
consensus.consensusID++
consensus.Log.Debug("HOORAY!!! CONSENSUS REACHED!!!", "consensusID", consensus.consensusID)
// TODO: reconstruct the whole block from header and transactions
// For now, we used the stored whole block already stored in consensus.blockHeader

@ -16,7 +16,7 @@ func (consensus *Consensus) constructAnnounceMessage() []byte {
// 4 byte consensus id
fourBytes := make([]byte, 4)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusId)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusID)
buffer.Write(fourBytes)
// 32 byte block hash
@ -44,7 +44,7 @@ func (consensus *Consensus) constructChallengeMessage(msgTypeToSend proto_consen
// 4 byte consensus id
fourBytes := make([]byte, 4)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusId)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusID)
buffer.Write(fourBytes)
// 32 byte block hash
@ -94,7 +94,7 @@ func (consensus *Consensus) constructCollectiveSigMessage(collectiveSig [64]byte
// 4 byte consensus id
fourBytes := make([]byte, 4)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusId)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusID)
buffer.Write(fourBytes)
// 32 byte block hash

@ -2,37 +2,37 @@ package consensus
// Consensus state enum for both leader and validator
// States for leader:
// FINISHED, ANNOUNCE_DONE, CHALLENGE_DONE
// FINISHED, AnnounceDone, ChallengeDone
// States for validator:
// FINISHED, COMMIT_DONE, RESPONSE_DONE
// FINISHED, CommitDone, ResponseDone
type ConsensusState int
const (
FINISHED ConsensusState = iota // initial state or state after previous consensus is done.
ANNOUNCE_DONE
COMMIT_DONE
CHALLENGE_DONE
RESPONSE_DONE
COLLECTIVE_SIG_DONE
FINAL_COMMIT_DONE
FINAL_CHALLENGE_DONE
FINAL_RESPONSE_DONE
AnnounceDone
CommitDone
ChallengeDone
ResponseDone
CollectiveSigDone
FinalCommitDone
FinalChallengeDone
FinalResponseDone
)
// Returns string name for the ConsensusState enum
func (state ConsensusState) String() string {
names := [...]string{
"FINISHED",
"ANNOUNCE_DONE",
"COMMIT_DONE",
"CHALLENGE_DONE",
"RESPONSE_DONE",
"COLLECTIVE_SIG_DONE",
"FINAL_COMMIT_DONE",
"FINAL_CHALLENGE_DONE",
"FINAL_RESPONSE_DONE"}
"AnnounceDone",
"CommitDone",
"ChallengeDone",
"ResponseDone",
"CollectiveSigDone",
"FinalCommitDone",
"FinalChallengeDone",
"FinalResponseDone"}
if state < FINISHED || state > FINAL_RESPONSE_DONE {
if state < FINISHED || state > FinalResponseDone {
return "Unknown"
}
return names[state]

@ -10,8 +10,8 @@ func TestNewConsensus(test *testing.T) {
leader := p2p.Peer{Ip: "1", Port: "2"}
validator := p2p.Peer{Ip: "3", Port: "5"}
consensus := NewConsensus("1", "2", "0", []p2p.Peer{leader, validator}, leader)
if consensus.consensusId != 0 {
test.Errorf("Consensus Id is initialized to the wrong value: %d", consensus.consensusId)
if consensus.consensusID != 0 {
test.Errorf("Consensus Id is initialized to the wrong value: %d", consensus.consensusID)
}
if consensus.IsLeader != true {

@ -32,9 +32,9 @@ func (consensus *Consensus) ProcessMessageValidator(message []byte) {
case proto_consensus.ANNOUNCE:
consensus.processAnnounceMessage(payload)
case proto_consensus.CHALLENGE:
consensus.processChallengeMessage(payload, RESPONSE_DONE)
consensus.processChallengeMessage(payload, ResponseDone)
case proto_consensus.FINAL_CHALLENGE:
consensus.processChallengeMessage(payload, FINAL_RESPONSE_DONE)
consensus.processChallengeMessage(payload, FinalResponseDone)
case proto_consensus.COLLECTIVE_SIG:
consensus.processCollectiveSigMessage(payload)
default:
@ -48,7 +48,7 @@ func (consensus *Consensus) processAnnounceMessage(payload []byte) {
//#### Read payload data
offset := 0
// 4 byte consensus id
consensusId := binary.BigEndian.Uint32(payload[offset : offset+4])
consensusID := binary.BigEndian.Uint32(payload[offset : offset+4])
offset += 4
// 32 byte block hash
@ -95,7 +95,7 @@ func (consensus *Consensus) processAnnounceMessage(payload []byte) {
}
consensus.blockHeader = blockHeader // TODO: think about remove this field and use blocksReceived instead
consensus.mutex.Lock()
consensus.blocksReceived[consensusId] = &BlockConsensusStatus{blockHeader, consensus.state}
consensus.blocksReceived[consensusID] = &BlockConsensusStatus{blockHeader, consensus.state}
consensus.mutex.Unlock()
// Add attack model of IncorrectResponse.
@ -105,8 +105,8 @@ func (consensus *Consensus) processAnnounceMessage(payload []byte) {
}
// check consensus Id
if consensusId != consensus.consensusId {
consensus.Log.Warn("Received message with wrong consensus Id", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
if consensusID != consensus.consensusID {
consensus.Log.Warn("Received message with wrong consensus Id", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
return
}
@ -124,13 +124,13 @@ func (consensus *Consensus) processAnnounceMessage(payload []byte) {
secret, msgToSend := consensus.constructCommitMessage(proto_consensus.COMMIT)
// Store the commitment secret
consensus.secret[consensusId] = secret
consensus.secret[consensusID] = secret
p2p.SendMessage(consensus.leader, msgToSend)
// consensus.Log.Warn("Sending Commit to leader", "state", targetState)
// Set state to COMMIT_DONE
consensus.state = COMMIT_DONE
// Set state to CommitDone
consensus.state = CommitDone
}
// Processes the challenge message sent from the leader
@ -138,7 +138,7 @@ func (consensus *Consensus) processChallengeMessage(payload []byte, targetState
//#### Read payload data
offset := 0
// 4 byte consensus id
consensusId := binary.BigEndian.Uint32(payload[offset : offset+4])
consensusID := binary.BigEndian.Uint32(payload[offset : offset+4])
offset += 4
// 32 byte block hash
@ -167,7 +167,7 @@ func (consensus *Consensus) processChallengeMessage(payload []byte, targetState
//#### END: Read payload data
// Update readyByConsensus for attack.
attack.GetInstance().UpdateConsensusReady(consensusId)
attack.GetInstance().UpdateConsensusReady(consensusID)
// Verify block data and the aggregated signatures
// check leader Id
@ -199,9 +199,9 @@ func (consensus *Consensus) processChallengeMessage(payload []byte, targetState
}
// check consensus Id
if consensusId != consensus.consensusId {
consensus.Log.Warn("Received message with wrong consensus Id", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
if _, ok := consensus.blocksReceived[consensus.consensusId]; !ok {
if consensusID != consensus.consensusID {
consensus.Log.Warn("Received message with wrong consensus Id", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
if _, ok := consensus.blocksReceived[consensus.consensusID]; !ok {
return
}
consensus.Log.Warn("ROLLING UP", "consensus", consensus)
@ -233,33 +233,33 @@ func (consensus *Consensus) processChallengeMessage(payload []byte, targetState
return
}
response, err := crypto.Response(crypto.Ed25519Curve, consensus.priKey, consensus.secret[consensusId], receivedChallenge)
response, err := crypto.Response(crypto.Ed25519Curve, consensus.priKey, consensus.secret[consensusID], receivedChallenge)
if err != nil {
log.Warn("Failed to generate response", "err", err)
return
}
msgTypeToSend := proto_consensus.RESPONSE
if targetState == FINAL_RESPONSE_DONE {
msgTypeToSend = proto_consensus.FINAL_RESPONSE
if targetState == FinalResponseDone {
msgTypeToSend = proto_consensus.FinalResponse
}
msgToSend := consensus.constructResponseMessage(msgTypeToSend, response)
p2p.SendMessage(consensus.leader, msgToSend)
// consensus.Log.Warn("Sending Response to leader", "state", targetState)
// Set state to target state (RESPONSE_DONE, FINAL_RESPONSE_DONE)
// Set state to target state (ResponseDone, FinalResponseDone)
consensus.state = targetState
if consensus.state == FINAL_RESPONSE_DONE {
if consensus.state == FinalResponseDone {
// BIG TODO: the block catch up logic is basically a mock now. More checks need to be done to make it correct.
// The logic is to roll up to the latest blocks one by one to try catching up with the leader.
for {
val, ok := consensus.blocksReceived[consensus.consensusId]
val, ok := consensus.blocksReceived[consensus.consensusID]
if ok {
delete(consensus.blocksReceived, consensus.consensusId)
delete(consensus.blocksReceived, consensus.consensusID)
consensus.blockHash = [32]byte{}
delete(consensus.secret, consensusId)
consensus.consensusId++ // roll up one by one, until the next block is not received yet.
delete(consensus.secret, consensusID)
consensus.consensusID++ // roll up one by one, until the next block is not received yet.
// TODO: think about when validators know about the consensus is reached.
// For now, the blockchain is updated right here.
@ -274,7 +274,7 @@ func (consensus *Consensus) processChallengeMessage(payload []byte, targetState
}
// check block data (transactions
if !consensus.BlockVerifier(&blockHeaderObj) {
consensus.Log.Debug("[WARNING] Block content is not verified successfully", "consensusId", consensus.consensusId)
consensus.Log.Debug("[WARNING] Block content is not verified successfully", "consensusID", consensus.consensusID)
return
}
consensus.Log.Info("Finished Response. Adding block to chain", "numTx", len(blockHeaderObj.Transactions))
@ -292,7 +292,7 @@ func (consensus *Consensus) processCollectiveSigMessage(payload []byte) {
//#### Read payload data
offset := 0
// 4 byte consensus id
consensusId := binary.BigEndian.Uint32(payload[offset : offset+4])
consensusID := binary.BigEndian.Uint32(payload[offset : offset+4])
offset += 4
// 32 byte block hash
@ -336,7 +336,7 @@ func (consensus *Consensus) processCollectiveSigMessage(payload []byte) {
// Verify collective signature
err := crypto.Verify(crypto.Ed25519Curve, consensus.publicKeys, payload[:36], append(collectiveSig, bitmap...), crypto.NewThresholdPolicy((2*len(consensus.publicKeys)/3)+1))
if err != nil {
consensus.Log.Warn("Failed to verify the collective sig message", "consensusId", consensusId, "err", err)
consensus.Log.Warn("Failed to verify the collective sig message", "consensusID", consensusID, "err", err)
return
}
@ -347,8 +347,8 @@ func (consensus *Consensus) processCollectiveSigMessage(payload []byte) {
}
// check consensus Id
if consensusId != consensus.consensusId {
consensus.Log.Warn("Received message with wrong consensus Id", "myConsensusId", consensus.consensusId, "theirConsensusId", consensusId, "consensus", consensus)
if consensusID != consensus.consensusID {
consensus.Log.Warn("Received message with wrong consensus Id", "myConsensusId", consensus.consensusID, "theirConsensusId", consensusID, "consensus", consensus)
return
}
@ -358,12 +358,12 @@ func (consensus *Consensus) processCollectiveSigMessage(payload []byte) {
return
}
secret, msgToSend := consensus.constructCommitMessage(proto_consensus.FINAL_COMMIT)
secret, msgToSend := consensus.constructCommitMessage(proto_consensus.FinalCommit)
// Store the commitment secret
consensus.secret[consensusId] = secret
consensus.secret[consensusID] = secret
p2p.SendMessage(consensus.leader, msgToSend)
// Set state to COMMIT_DONE
consensus.state = FINAL_COMMIT_DONE
// Set state to CommitDone
consensus.state = FinalCommitDone
}

@ -3,6 +3,7 @@ package consensus
import (
"bytes"
"encoding/binary"
"github.com/dedis/kyber"
"github.com/simple-rules/harmony-benchmark/crypto"
proto_consensus "github.com/simple-rules/harmony-benchmark/proto/consensus"
@ -14,7 +15,7 @@ func (consensus *Consensus) constructCommitMessage(msgType proto_consensus.Messa
// 4 byte consensus id
fourBytes := make([]byte, 4)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusId)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusID)
buffer.Write(fourBytes)
// 32 byte block hash
@ -42,7 +43,7 @@ func (consensus *Consensus) constructResponseMessage(msgType proto_consensus.Mes
// 4 byte consensus id
fourBytes := make([]byte, 4)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusId)
binary.BigEndian.PutUint32(fourBytes, consensus.consensusID)
buffer.Write(fourBytes)
// 32 byte block hash

@ -108,13 +108,13 @@ func (node *Node) NodeHandler(conn net.Conn) {
node.Client.UpdateBlocks(*blocks)
}
}
case proto_node.BLOCKCHAIN_SYNC:
case proto_node.BlockchainSync:
node.handleBlockchainSync(msgPayload, conn)
case proto_node.CLIENT:
clientMsgType := proto_node.ClientMessageType(msgPayload[0])
switch clientMsgType {
case proto_node.LOOKUP_UTXO:
decoder := gob.NewDecoder(bytes.NewReader(msgPayload[1:])) // skip the LOOKUP_UTXO messge type
case proto_node.LookupUtxo:
decoder := gob.NewDecoder(bytes.NewReader(msgPayload[1:])) // skip the LookupUtxo messge type
fetchUtxoMessage := new(proto_node.FetchUtxoMessage)
decoder.Decode(fetchUtxoMessage)
@ -188,11 +188,11 @@ FOR_LOOP:
for {
syncMsgType := proto_node.BlockchainSyncMessageType(payload[0])
switch syncMsgType {
case proto_node.GET_BLOCK:
case proto_node.GetBlock:
block := node.blockchain.FindBlock(payload[1:33])
w.Write(block.Serialize())
w.Flush()
case proto_node.GET_LAST_BLOCK_HASHES:
case proto_node.GetLastBlockHashes:
blockchainSyncMessage := proto_node.BlockchainSyncMessage{
BlockHeight: len(node.blockchain.Blocks),
BlockHashes: node.blockchain.GetBlockHashes(),
@ -217,7 +217,7 @@ FOR_LOOP:
msgType, err := proto.GetMessageType(content)
actionType := proto_node.NodeMessageType(msgType)
if err != nil || actionType != proto_node.BLOCKCHAIN_SYNC {
if err != nil || actionType != proto_node.BlockchainSync {
node.log.Error("Failed in reading message type from syncing node", err)
return
}

@ -20,8 +20,8 @@ const (
type TransactionMessageType int
const (
PROOF_OF_LOCK TransactionMessageType = iota // The proof of accept or reject returned by the leader to the client tnat issued cross shard transactions.
UTXO_RESPONSE
ProofOfLock TransactionMessageType = iota // The proof of accept or reject returned by the leader to the client tnat issued cross shard transactions.
UtxoResponse
)
type FetchUtxoResponseMessage struct {
@ -33,7 +33,7 @@ type FetchUtxoResponseMessage struct {
func ConstructProofOfAcceptOrRejectMessage(proofs []blockchain.CrossShardTxProof) []byte {
byteBuffer := bytes.NewBuffer([]byte{byte(proto.CLIENT)})
byteBuffer.WriteByte(byte(Transaction))
byteBuffer.WriteByte(byte(PROOF_OF_LOCK))
byteBuffer.WriteByte(byte(ProofOfLock))
encoder := gob.NewEncoder(byteBuffer)
encoder.Encode(proofs)
@ -44,7 +44,7 @@ func ConstructProofOfAcceptOrRejectMessage(proofs []blockchain.CrossShardTxProof
func ConstructFetchUtxoResponseMessage(utxoMap *blockchain.UtxoMap, shardID uint32) []byte {
byteBuffer := bytes.NewBuffer([]byte{byte(proto.CLIENT)})
byteBuffer.WriteByte(byte(Transaction))
byteBuffer.WriteByte(byte(UTXO_RESPONSE))
byteBuffer.WriteByte(byte(UtxoResponse))
encoder := gob.NewEncoder(byteBuffer)
encoder.Encode(FetchUtxoResponseMessage{*utxoMap, shardID})

@ -69,7 +69,7 @@ RESPONSE:
*/
// the number of bytes consensus message type occupies
const CONSENSUS_MESSAGE_TYPE_BYTES = 1
const ConsensusMessageTypeBytes = 1
// The specific types of message under CONSENSUS category
type ConsensusMessageType byte
@ -89,10 +89,10 @@ const (
CHALLENGE
RESPONSE
COLLECTIVE_SIG
FINAL_COMMIT
FinalCommit
FINAL_CHALLENGE
FINAL_RESPONSE
START_CONSENSUS
FinalResponse
StartConsensus
)
// Returns string name for the MessageType enum
@ -103,13 +103,13 @@ func (msgType MessageType) String() string {
"CHALLENGE",
"RESPONSE",
"COLLECTIVE_SIG",
"FINAL_COMMIT",
"FinalCommit",
"FINAL_CHALLENGE",
"FINAL_RESPONSE",
"START_CONSENSUS",
"FinalResponse",
"StartConsensus",
}
if msgType < ANNOUNCE || msgType > START_CONSENSUS {
if msgType < ANNOUNCE || msgType > StartConsensus {
return "Unknown"
}
return names[msgType]
@ -128,7 +128,7 @@ func GetConsensusMessagePayload(message []byte) ([]byte, error) {
if len(message) < 2 {
return []byte{}, errors.New("Failed to get consensus message payload: no data available.")
}
return message[CONSENSUS_MESSAGE_TYPE_BYTES:], nil
return message[ConsensusMessageTypeBytes:], nil
}
// Concatenate msgType as one byte with payload, and return the whole byte array

@ -18,7 +18,7 @@ const (
BLOCK
CLIENT
CONTROL
BLOCKCHAIN_SYNC
BlockchainSync
// TODO: add more types
)
@ -33,8 +33,8 @@ type BlockchainSyncMessageType int
const (
DONE BlockchainSyncMessageType = iota
GET_LAST_BLOCK_HASHES
GET_BLOCK
GetLastBlockHashes
GetBlock
)
// TransactionMessageType representa the types of messages used for NODE/Transaction
@ -57,7 +57,7 @@ const (
type ClientMessageType int
const (
LOOKUP_UTXO ClientMessageType = iota
LookupUtxo ClientMessageType = iota
)
// The types of messages used for NODE/CONTROL
@ -112,7 +112,7 @@ func ConstructUnlockToCommitOrAbortMessage(txsAndProofs []*blockchain.Transactio
func ConstructFetchUtxoMessage(sender p2p.Peer, addresses [][20]byte) []byte {
byteBuffer := bytes.NewBuffer([]byte{byte(proto.NODE)})
byteBuffer.WriteByte(byte(CLIENT))
byteBuffer.WriteByte(byte(LOOKUP_UTXO))
byteBuffer.WriteByte(byte(LookupUtxo))
encoder := gob.NewEncoder(byteBuffer)
encoder.Encode(FetchUtxoMessage{Addresses: addresses, Sender: sender})
@ -141,9 +141,9 @@ func ConstructTransactionListMessage(transactions []*blockchain.Transaction) []b
// ConstructBlockchainSyncMessage constructs Blockchain Sync Message.
func ConstructBlockchainSyncMessage(msgType BlockchainSyncMessageType, blockHash [32]byte) []byte {
byteBuffer := bytes.NewBuffer([]byte{byte(proto.NODE)})
byteBuffer.WriteByte(byte(BLOCKCHAIN_SYNC))
byteBuffer.WriteByte(byte(BlockchainSync))
byteBuffer.WriteByte(byte(msgType))
if msgType != GET_LAST_BLOCK_HASHES {
if msgType != GetLastBlockHashes {
byteBuffer.Write(blockHash[:])
}
return byteBuffer.Bytes()

@ -1,3 +1,3 @@
# the hex is basically 0, 0034, 0, 0, 4, "9001 9002 9003 9004 9005 9006 9007 9008 9009 9010"
# explanation: p2p type, size(52 bytes), msg category, action type, START_CONSENSUS, payload
# explanation: p2p type, size(52 bytes), msg category, action type, StartConsensus, payload
echo -e '\x00\x00\x00\x00\x34\x00\x00\x04\x39\x30\x30\x31\x20\x39\x30\x30\x32\x20\x39\x30\x30\x33\x20\x39\x30\x30\x34\x20\x39\x30\x30\x35\x20\x39\x30\x30\x36\x20\x39\x30\x30\x37\x20\x39\x30\x30\x38\x20\x39\x30\x30\x39\x20\x39\x30\x31\x30' | nc 127.0.0.1 9000

@ -74,7 +74,7 @@ LOOP_HONEST_NODE:
}
go func(peerConfig *SyncPeerConfig) {
defer wg.Done()
msg := proto_node.ConstructBlockchainSyncMessage(proto_node.GET_LAST_BLOCK_HASHES, [32]byte{})
msg := proto_node.ConstructBlockchainSyncMessage(proto_node.GetLastBlockHashes, [32]byte{})
peerConfig.w.Write(msg)
peerConfig.w.Flush()
var content []byte
@ -128,7 +128,7 @@ TASK_LOOP:
break
}
syncTask := task[0].(SyncBlockTask)
msg := proto_node.ConstructBlockchainSyncMessage(proto_node.GET_BLOCK, syncTask.blockHash)
msg := proto_node.ConstructBlockchainSyncMessage(proto_node.GetBlock, syncTask.blockHash)
peerConfig.w.Write(msg)
peerConfig.w.Flush()
var content []byte

Loading…
Cancel
Save