diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml new file mode 100644 index 0000000..2859f3f --- /dev/null +++ b/.github/workflows/linter.yaml @@ -0,0 +1,23 @@ +name: linter + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: stable + - name: golangci-lint + uses: golangci/golangci-lint-action@v6 + with: + version: v1.64.5 \ No newline at end of file diff --git a/internal/blockchain/utils.go b/internal/blockchain/utils.go index e33d362..64d1549 100644 --- a/internal/blockchain/utils.go +++ b/internal/blockchain/utils.go @@ -56,15 +56,15 @@ func areStakesEqual(m1, m2 map[string]int) bool { return true } -func (t *Transaction) PrintTx() { - fmt.Printf("\nTID: %x\n", t.TID) - fmt.Printf("Type: %d\n", t.Type) - fmt.Printf("Timestamp: %d\n", t.Timestamp) - fmt.Printf("DomainName: %s\n", t.DomainName) - fmt.Printf("IP: %s\n", t.IP) - fmt.Printf("TTL: %d\n", t.TTL) - fmt.Printf("OwnerKey: %s\n", t.OwnerKey) - fmt.Printf("Signature: %d\n\n", t.Signature) +func (tx *Transaction) PrintTx() { + fmt.Printf("\nTID: %x\n", tx.TID) + fmt.Printf("Type: %d\n", tx.Type) + fmt.Printf("Timestamp: %d\n", tx.Timestamp) + fmt.Printf("DomainName: %s\n", tx.DomainName) + fmt.Printf("IP: %s\n", tx.IP) + fmt.Printf("TTL: %d\n", tx.TTL) + fmt.Printf("OwnerKey: %s\n", tx.OwnerKey) + fmt.Printf("Signature: %d\n\n", tx.Signature) } func (b *Block) PrintBlock() { diff --git a/internal/consensus/drg.go b/internal/consensus/drg.go index 3ea59a8..dc5a544 100644 --- a/internal/consensus/drg.go +++ b/internal/consensus/drg.go @@ -9,8 +9,8 @@ import ( ) type SecretValues struct { - SecretValue int // u_i -> revealed to other registries - RandomValue int // r_i -> kept as a secret + SecretValue int // uI -> revealed to other registries + RandomValue int // rI -> kept as a secret } func CommitmentPhase(registryKeys [][]byte) (map[string]string, map[string]SecretValues) { @@ -18,13 +18,13 @@ func CommitmentPhase(registryKeys [][]byte) (map[string]string, map[string]Secre secretValues := make(map[string]SecretValues) numRegistries := len(registryKeys) - rand.Seed(time.Now().UnixNano()) + rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < numRegistries; i++ { - u_i := rand.Intn(1000) + 1 - r_i := rand.Intn(1000) + 1 + uI := rand.Intn(1000) + 1 + rI := rand.Intn(1000) + 1 - data := fmt.Sprintf("%d%d", r_i, u_i) + data := fmt.Sprintf("%d%d", rI, uI) hash := sha256.Sum256([]byte(data)) commitment := fmt.Sprintf("%x", hash) // stored in hexa @@ -33,8 +33,8 @@ func CommitmentPhase(registryKeys [][]byte) (map[string]string, map[string]Secre // Store secret values secretValues[hex.EncodeToString(registryKeys[i])] = SecretValues{ - SecretValue: u_i, - RandomValue: r_i, + SecretValue: uI, + RandomValue: rI, } } diff --git a/internal/consensus/pos.go b/internal/consensus/pos.go index 99f9689..5d97795 100644 --- a/internal/consensus/pos.go +++ b/internal/consensus/pos.go @@ -13,7 +13,7 @@ func GetSlotLeaderUtil(registryKeys [][]byte, stakeData map[string]int, epochRan for index, registry := range registryKeys { registryStr := hex.EncodeToString(registry) stakeProbs := GetStakes(stakeData, index) - + prob := stakeProbs[registryStr] cumulativeProb += prob @@ -31,9 +31,9 @@ func GetStakes(stakeData map[string]int, index int) map[string]float64 { // create a slice of the keys keys := make([]string, 0, len(stakeData)) - for k := range stakeData { - keys = append(keys, k) - } + for k := range stakeData { + keys = append(keys, k) + } for i := index; i < len(keys); i++ { sum += float64(stakeData[keys[i]]) diff --git a/internal/network/node.go b/internal/network/node.go index 5e83ae3..fc74bd7 100644 --- a/internal/network/node.go +++ b/internal/network/node.go @@ -2,16 +2,16 @@ package network import ( "context" - "encoding/json" + cryptorand "crypto/rand" "encoding/hex" + "encoding/json" "fmt" "log" - "math/rand" "sync" "github.com/bleasey/bdns/internal/blockchain" - "github.com/bleasey/bdns/internal/index" "github.com/bleasey/bdns/internal/consensus" + "github.com/bleasey/bdns/internal/index" "github.com/libp2p/go-libp2p/core/network" ) @@ -31,7 +31,7 @@ type Node struct { Blockchain *blockchain.Blockchain BcMutex sync.Mutex RandomNumber []byte - RandomMutex sync.Mutex + RandomMutex sync.Mutex EpochRandoms map[int64]map[string]consensus.SecretValues } @@ -43,10 +43,10 @@ type NodeConfig struct { } type RandomNumberMsg struct { - Epoch int64 - SecretValue int // u_i value - RandomValue int // r_i value - Sender []byte // Registry's public key + Epoch int64 + SecretValue int // uI value + RandomValue int // rI value + Sender []byte // Registry's public key } // NewNode initializes a blockchain node @@ -74,16 +74,16 @@ func NewNode(ctx context.Context, addr string, topicName string) (*Node, error) } func (n *Node) GenerateRandomNumber() []byte { - n.RandomMutex.Lock() - defer n.RandomMutex.Unlock() - - randomBytes := make([]byte, 32) - if _, err := rand.Read(randomBytes); err != nil { - log.Panic("Failed to generate random number:", err) - } - - n.RandomNumber = randomBytes - return randomBytes + n.RandomMutex.Lock() + defer n.RandomMutex.Unlock() + + randomBytes := make([]byte, 32) + if _, err := cryptorand.Read(randomBytes); err != nil { + log.Panic("Failed to generate random number:", err) + } + + n.RandomNumber = randomBytes + return randomBytes } // HandleGossip listens for messages from the gossip network @@ -115,13 +115,13 @@ func (n *Node) HandleGossip() { n.AddBlock(&block) case MsgRandomNumber: - var randomMsg RandomNumberMsg - err := json.Unmarshal(msg.Content, &randomMsg) - if err != nil { - log.Println("Failed to unmarshal random number message:", err) - continue - } - n.RandomNumberHandler(randomMsg.Epoch, hex.EncodeToString(randomMsg.Sender), randomMsg.SecretValue, randomMsg.RandomValue) // Store the received random number + var randomMsg RandomNumberMsg + err := json.Unmarshal(msg.Content, &randomMsg) + if err != nil { + log.Println("Failed to unmarshal random number message:", err) + continue + } + n.RandomNumberHandler(randomMsg.Epoch, hex.EncodeToString(randomMsg.Sender), randomMsg.SecretValue, randomMsg.RandomValue) // Store the received random number // case MsgChainRequest: // n.Blockchain.SendBlockchain(conn) @@ -170,18 +170,18 @@ func (n *Node) MakeDNSRequest(domainName string) { n.P2PNetwork.BroadcastMessage(DNSRequest, req) } -func (n *Node) BroadcastRandomNumber(epoch int64, registryKeys [][]byte) { +func (n *Node) BroadcastRandomNumber(epoch int64) { _, secretValues := consensus.CommitmentPhase(n.RegistryKeys) nodeSecretValues := secretValues[hex.EncodeToString(n.KeyPair.PublicKey)] msg := RandomNumberMsg{ - Epoch: epoch, + Epoch: epoch, SecretValue: nodeSecretValues.SecretValue, RandomValue: nodeSecretValues.RandomValue, - Sender: n.KeyPair.PublicKey, + Sender: n.KeyPair.PublicKey, } n.RandomNumberHandler(epoch, hex.EncodeToString(n.KeyPair.PublicKey), nodeSecretValues.SecretValue, nodeSecretValues.RandomValue) - n.P2PNetwork.BroadcastMessage(MsgRandomNumber, msg) + n.P2PNetwork.BroadcastMessage(MsgRandomNumber, msg) } func (n *Node) DNSRequestHandler(req BDNSRequest, reqSender string) { @@ -209,16 +209,16 @@ func (n *Node) DNSResponseHandler(res BDNSResponse) { func (n *Node) RandomNumberHandler(epoch int64, sender string, secretValue int, randomValue int) { n.RandomMutex.Lock() defer n.RandomMutex.Unlock() - + if n.EpochRandoms == nil { n.EpochRandoms = make(map[int64]map[string]consensus.SecretValues) } if n.EpochRandoms[epoch] == nil { - n.EpochRandoms[epoch] = make(map[string]consensus.SecretValues) - } + n.EpochRandoms[epoch] = make(map[string]consensus.SecretValues) + } - n.EpochRandoms[epoch][sender] = consensus.SecretValues{ + n.EpochRandoms[epoch][sender] = consensus.SecretValues{ SecretValue: secretValue, RandomValue: randomValue, } diff --git a/internal/network/node_helper.go b/internal/network/node_helper.go index e771435..96853b6 100644 --- a/internal/network/node_helper.go +++ b/internal/network/node_helper.go @@ -44,7 +44,6 @@ func (n *Node) AddBlock(block *blockchain.Block) { n.Blockchain.AddBlock(block) } - func (n *Node) AddTransaction(tx *blockchain.Transaction) { n.TxMutex.Lock() defer n.TxMutex.Unlock() @@ -92,7 +91,7 @@ func (n *Node) CreateBlockIfLeader(epochInterval int64) { fmt.Println("Node", n.Address, "is the slot leader for the genesis block") seedBytes := []byte(fmt.Sprintf("%f", n.Config.Seed)) - genesisBlock := blockchain.NewGenesisBlock(currSlotLeader, &n.KeyPair.PrivateKey, n.RegistryKeys, seedBytes) + genesisBlock := blockchain.NewGenesisBlock(currSlotLeader, &n.KeyPair.PrivateKey, n.RegistryKeys, seedBytes) n.BcMutex.Lock() n.Blockchain.AddBlock(genesisBlock) n.BcMutex.Unlock() @@ -135,6 +134,6 @@ func (n *Node) CreateBlockIfLeader(epochInterval int64) { fmt.Print("Block ", newBlock.Index, " created and broadcasted by node ", n.Address, "\n\n") } - n.BroadcastRandomNumber(epoch + 1, n.RegistryKeys) // Send the rand nums to be used for next epoch + n.BroadcastRandomNumber(epoch + 1) // Send the rand nums to be used for next epoch } } diff --git a/internal/network/p2p.go b/internal/network/p2p.go index 73e0bf5..859edae 100644 --- a/internal/network/p2p.go +++ b/internal/network/p2p.go @@ -6,7 +6,7 @@ import ( "log" "github.com/libp2p/go-libp2p" - "github.com/libp2p/go-libp2p-pubsub" + pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/peer" "github.com/multiformats/go-multiaddr" @@ -100,7 +100,10 @@ func (p *P2PNetwork) BroadcastMessage(msgType MessageType, content interface{}) } msgData, _ := json.Marshal(gossipMsg) - p.Topic.Publish(context.Background(), msgData) + + if err := p.Topic.Publish(context.Background(), msgData); err != nil { + log.Println("Failed to publish message:", err) + } } // DirectMessage sends a message to a specific peer @@ -125,7 +128,9 @@ func (p *P2PNetwork) DirectMessage(msgType MessageType, content interface{}, pee Content: data, } - json.NewEncoder(stream).Encode(responseMsg) + if err := json.NewEncoder(stream).Encode(responseMsg); err != nil { + log.Println("Failed to encode message:", err) + } } // ConnectToPeer connects to another peer via multiaddress diff --git a/internal/network/server.go b/internal/network/server.go index c6763fd..19243f4 100644 --- a/internal/network/server.go +++ b/internal/network/server.go @@ -1,9 +1,9 @@ package network import ( + "encoding/hex" "fmt" "log" - "encoding/hex" "net" ) diff --git a/main.go b/main.go index 2518061..7101f67 100644 --- a/main.go +++ b/main.go @@ -5,5 +5,5 @@ import ( ) func main() { - sims.SimGossip() // Runs a simple bdns p2p-gossip sim with 4 peers + sims.SimGossip() // Runs a simple bdns p2p-gossip sim with 6 peers } diff --git a/sims/gossip.go b/sims/gossip.go index 373b95f..7817248 100644 --- a/sims/gossip.go +++ b/sims/gossip.go @@ -64,4 +64,4 @@ func SimGossip() { wg.Wait() // Wait for queries to complete network.NodesCleanup(nodes) // Cleanup chaindata directory -} \ No newline at end of file +}