Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documents to the function (irishandler) #3

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions chains/cosmos/conn/secret_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,9 @@ func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
return sc.conn.(net.Conn).SetWriteDeadline(t)
}

// genEphKeys generates the Ephemeral key- pair.
// A cryptographic key is called Ephemeral if it is generated
// for each execution of a key establishment process.
func genEphKeys() (ephPub, ephPriv *[32]byte) {
var err error
ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
Expand All @@ -265,6 +268,7 @@ func genEphKeys() (ephPub, ephPriv *[32]byte) {
return
}

// shareEphPubKey shares the generated Ephemeral key-pair
func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {

// Send our pubkey and receive theirs in tandem.
Expand Down Expand Up @@ -335,6 +339,8 @@ var blacklist = [][32]byte{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
}

// hasSmallOrder is used to check the if the Empherial key
// generated has small order or not
func hasSmallOrder(pubKey [32]byte) bool {
isSmallOrderPoint := false
for _, bl := range blacklist {
Expand All @@ -346,6 +352,9 @@ func hasSmallOrder(pubKey [32]byte) bool {
return isSmallOrderPoint
}

// Creates hash function according to challenge, generally the
// hash function created is encrypted with 256 bytes and here the
// last 32 bytes has been encrypted for the challenge
func deriveSecretAndChallenge(dhSecret *[32]byte, locIsLeast bool) (recvSecret, sendSecret *[aeadKeySize]byte, challenge *[32]byte) {
hash := sha256.New
hkdf := hkdf.New(hash, dhSecret[:], nil, []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN"))
Expand Down Expand Up @@ -418,6 +427,8 @@ type authSigMessage struct {
Sig []byte
}

// Used in MakeSecretConnection and used to share the
// Authentic Share
func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {

// Send our info and receive theirs in tandem.
Expand Down
18 changes: 18 additions & 0 deletions chains/cosmos/conn/secret_connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type kvstoreConn struct {
*io.PipeWriter
}

// Close function will close the established connection
func (drw kvstoreConn) Close() (err error) {
err2 := drw.PipeWriter.CloseWithError(io.EOF)
err1 := drw.PipeReader.Close()
Expand All @@ -44,6 +45,9 @@ func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) {
return kvstoreConn{fooReader, fooWriter}, kvstoreConn{barReader, barWriter}
}

// makeSecretConnPair Establishes the secret connection pair
// Also makes sure that the connection has been established
// successfully, if not established successfully then return an error
func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) {

var fooConn, barConn = makeKVStoreConnPair()
Expand Down Expand Up @@ -92,6 +96,7 @@ func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection
return
}

// Tests the Handshake of Secret Connections
func TestSecretConnectionHandshake(t *testing.T) {
fooSecConn, barSecConn := makeSecretConnPair(t)
if err := fooSecConn.Close(); err != nil {
Expand Down Expand Up @@ -145,6 +150,7 @@ func TestComputeDHFailsOnLowOrder(t *testing.T) {
}
}

// Test for concurrent write
func TestConcurrentWrite(t *testing.T) {
fooSecConn, barSecConn := makeSecretConnPair(t)
fooWriteText := cmn.RandStr(dataMaxSize)
Expand All @@ -167,6 +173,7 @@ func TestConcurrentWrite(t *testing.T) {
}
}

// Test for concurrent read
func TestConcurrentRead(t *testing.T) {
fooSecConn, barSecConn := makeSecretConnPair(t)
fooWriteText := cmn.RandStr(dataMaxSize)
Expand All @@ -189,6 +196,7 @@ func TestConcurrentRead(t *testing.T) {
}
}

// writeLots writes in the fooSecConn, if not then return an error
func writeLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, txt string, n int) {
defer wg.Done()
for i := 0; i < n; i++ {
Expand All @@ -200,6 +208,7 @@ func writeLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, txt string, n in
}
}

// reads from fooSecConn
func readLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, n int) {
readBuffer := make([]byte, dataMaxSize)
for i := 0; i < n; i++ {
Expand All @@ -209,6 +218,9 @@ func readLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, n int) {
wg.Done()
}

// Test the secret connection has been established or not
// Also checks if the connection can read or write from node
// and even check the accurate number of bytes to be written
func TestSecretConnectionReadWrite(t *testing.T) {
fooConn, barConn := makeKVStoreConnPair()
fooWrites, barWrites := []string{}, []string{}
Expand Down Expand Up @@ -375,6 +387,8 @@ func (pk privKeyWithNilPubKey) Sign(msg []byte) ([]byte, error) { return pk.orig
func (pk privKeyWithNilPubKey) PubKey() crypto.PubKey { return nil }
func (pk privKeyWithNilPubKey) Equals(pk2 crypto.PrivKey) bool { return pk.orig.Equals(pk2) }

// TestNilPubkey checks if ed25519 public key has been
// generated, otherwise return error
func TestNilPubkey(t *testing.T) {
var fooConn, barConn = makeKVStoreConnPair()
var fooPrvKey = ed25519.GenPrivKey()
Expand All @@ -393,6 +407,10 @@ func TestNilPubkey(t *testing.T) {
})
}

// TestNonEd25519Pubkey tests if public key ed25519 has been
// genreated or the secp256k1.PubKeySecp256k1 has been
// generated, if secp256k1.PubKeySecp256k1 has been genreated
// then it will throw the error of "secp256k1.PubKeySecp256k1"
func TestNonEd25519Pubkey(t *testing.T) {
var fooConn, barConn = makeKVStoreConnPair()
var fooPrvKey = ed25519.GenPrivKey()
Expand Down
55 changes: 51 additions & 4 deletions chains/cosmos/handlerCosmos.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ var ServicedTMCore chains.NodeType = chains.NodeType{Version: "0.32.13", Network

// ---------------------- DATA CONNECT INTERFACE --------------------------------

//RunDataConnect checks for errors while making connection with the base.
// This Error may include base connection establishment, creating TM Handler,
// handhsaking, upgrading connection of handshaking. It will also reattempt
// the connection.
func RunDataConnect(peerAddr string,
marlinTo chan marlinTypes.MarlinMessage,
marlinFrom chan marlinTypes.MarlinMessage,
Expand Down Expand Up @@ -93,6 +97,9 @@ func RunDataConnect(peerAddr string,
}
}

// dialPeer will check if the Peer has dialed succesfully or not,
// if there are errors found while dialling the connection then it
// will return an error to RunDataConnect, otherwise return "nil"
func (h *TendermintHandler) dialPeer() error {
var err error
h.baseConnection, err = net.DialTimeout("tcp", h.peerAddr, 2000*time.Millisecond)
Expand All @@ -103,6 +110,9 @@ func (h *TendermintHandler) dialPeer() error {
return nil
}

// acceptPeer will check the if the Peer has connected succesfully
// or not, if there are errors found while making an successful connection
// then it will return an error to RunDataConnect, otherwise return "nil"
func (h *TendermintHandler) acceptPeer() error {
log.Info("TMCore side listening for dials to ",
string(hex.EncodeToString(h.privateKey.PubKey().Address())), "@<SYSTEM-IP-ADDR>:", h.listenPort)
Expand All @@ -120,6 +130,10 @@ func (h *TendermintHandler) acceptPeer() error {
return nil
}

// upgradeConnectionAndHandshake establishes if there has been a secret
// connecton established or if there is a problem with handshaking.
// if no error has been captured, it will give a successful connection
// with Address and node info
func (h *TendermintHandler) upgradeConnectionAndHandshake() error {
var err error
h.secretConnection, err = conn.MakeSecretConnection(h.baseConnection, h.privateKey)
Expand All @@ -138,6 +152,12 @@ func (h *TendermintHandler) upgradeConnectionAndHandshake() error {
return nil
}

// handshake function follows the protocol set on amino spec,
// During the handshake the server client will exchange
// information required to establish the secure connection.
// Error encounterd while seniding handhshaking message or reciving
// using Amino spec will be checked here and
// returned to upgradeConnectionAndHandshake
func (h *TendermintHandler) handshake() error {
var (
errc = make(chan error, 2)
Expand Down Expand Up @@ -183,6 +203,8 @@ func (h *TendermintHandler) handshake() error {
return nil
}

// establishes a P2P connection with the TM Core
// sends and recives routines accordingly
func (h *TendermintHandler) beginServicing() error {
// Register Messages
RegisterPacket(h.codec)
Expand Down Expand Up @@ -215,6 +237,12 @@ func (h *TendermintHandler) beginServicing() error {
return nil
}

// Datas are recived by TM Core. sendRoutine sends PING
// and PONG message to TM Core. Basically, it will
// Sends PING messages to TM Core or Sends PONG messages
// to TM Core or Check if PONG messages are received
// in time or Block to Shut down sendRoutine or
// messages are recived from the marlin relay.
func (h *TendermintHandler) sendRoutine() {
log.Info("TMCore <- Connector Routine Started")

Expand Down Expand Up @@ -394,6 +422,9 @@ func (h *TendermintHandler) sendRoutine() {
}
}

// Data is processed and sent back
// Received PING and PONG messages from TM Core
// and Actual message packets are encoded from TM Core
func (h *TendermintHandler) recvRoutine() {
log.Info("TMCore -> Connector Routine Started")

Expand Down Expand Up @@ -618,7 +649,7 @@ FOR_LOOP:
// Drain
}
}

//decodes the Consensus Messages From the Channel Buffer
func (h *TendermintHandler) decodeConsensusMsgFromChannelBuffer(chanbuf []marlinTypes.PacketMsg) (ConsensusMessage, error) {
var databuf []byte
var msg ConsensusMessage
Expand All @@ -632,7 +663,7 @@ func (h *TendermintHandler) decodeConsensusMsgFromChannelBuffer(chanbuf []marlin
err = h.codec.UnmarshalBinaryBare(databuf, &msg)
return msg, err
}

// Stop the PONG time when the PING is called upon in recvRoutine
func (c *P2PConnection) stopPongTimer() {
if c.pongTimer != nil {
_ = c.pongTimer.Stop()
Expand Down Expand Up @@ -670,6 +701,10 @@ func RunSpamFilter(rpcAddr string,
handler.throughput.presentThroughput(5, handler.signalShutThroughput)
}

// Spam Filter executions begins from beginServicingSpamFilter
// this function will check for all possible spam at ingress point of Marlin Relay.
// Spam can also be produced from Marlin Relay. So beginServicingSpamFilter
// will also check for that.
func (h *TendermintHandler) beginServicingSpamFilter(id int) {
log.Info("Running TM side spam filter handler ", id)
// Register Messages
Expand Down Expand Up @@ -798,7 +833,7 @@ func (vote *Vote) SignBytes(chainID string, cdc *amino.Codec) []byte {
}
return bz
}

// Get the height of block chain
func (h *TendermintHandler) getValidators(height int64) ([]Validator, bool) {
if height+10 < h.maxValidHeight {
// Don't service messages too old
Expand Down Expand Up @@ -853,6 +888,11 @@ func (h *TendermintHandler) getValidators(height int64) ([]Validator, bool) {
}
}

// spamVerdictMessage used in beginServicingSpamFilter. This function
// return the Boolean value in beginServicingSpamFilter, according to
// boolean value. flow of this function gets executed. If the messages
// are recived in the form of 0x01 channel, it will allow the request
// to be proccessed, otherwise it will deny it
func (h *TendermintHandler) spamVerdictMessage(msg marlinTypes.MarlinMessage, allow bool) marlinTypes.MarlinMessage {
if allow {
return marlinTypes.MarlinMessage{
Expand All @@ -876,6 +916,8 @@ var isKeyFileUsed, memoized bool
var keyFileLocation string
var privateKey ed25519.PrivKeyEd25519

// Generates privatekey and publickey
// ED25519 Keypair is generated
func GenerateKeyFile(fileLocation string) {
log.Info("Generating KeyPair for cosmos-3-mainnet")

Expand Down Expand Up @@ -905,6 +947,7 @@ func GenerateKeyFile(fileLocation string) {
log.Info("Successfully written keyfile ", fileLocation)
}

// VerifyKeyFile verify's the 'key' file-location
func VerifyKeyFile(fileLocation string) (bool, error) {
log.Info("Accessing disk to extract info from KeyFile: ", fileLocation)
jsonFile, err := os.Open(fileLocation)
Expand Down Expand Up @@ -933,6 +976,8 @@ func VerifyKeyFile(fileLocation string) (bool, error) {
}
}

// This functions gets the private key from the keyfile!
// Also verifies the Keyfile integrity
func getPrivateKey() ed25519.PrivKeyEd25519 {
if !isKeyFileUsed {
return ed25519.GenPrivKey()
Expand Down Expand Up @@ -972,6 +1017,7 @@ func getPrivateKey() ed25519.PrivKeyEd25519 {
// ---------------------- COMMON UTILITIES ---------------------------------


//Creates Handler object between Marlin Relay and TM Core
func createTMHandler(peerAddr string,
rpcAddr string,
marlinTo chan marlinTypes.MarlinMessage,
Expand Down Expand Up @@ -1016,6 +1062,7 @@ func createTMHandler(peerAddr string,
}, nil
}

// This function display the logs/stats of SpamFilter
func (t *throughPutData) putInfo(direction string, key string, count uint32) {
t.mu.Lock()
switch direction {
Expand All @@ -1028,7 +1075,7 @@ func (t *throughPutData) putInfo(direction string, key string, count uint32) {
}
t.mu.Unlock()
}

// This function display the logs/stats of SpamFilter
func (t *throughPutData) presentThroughput(sec time.Duration, shutdownCh chan struct{}) {
for {
time.Sleep(sec * time.Second)
Expand Down
13 changes: 11 additions & 2 deletions chains/irisnet/conn/secret_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,9 @@ func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
return sc.conn.(net.Conn).SetWriteDeadline(t)
}

// genEphKeys generates the Ephemeral key- pair.
// A cryptographic key is called Ephemeral if it is generated
// for each execution of a key establishment process.
func genEphKeys() (ephPub, ephPriv *[32]byte) {
var err error
ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
Expand All @@ -264,7 +266,7 @@ func genEphKeys() (ephPub, ephPriv *[32]byte) {
}
return
}

// shareEphPubKey shares the generated Ephemeral key-pair
func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {

// Send our pubkey and receive theirs in tandem.
Expand Down Expand Up @@ -335,6 +337,8 @@ var blacklist = [][32]byte{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
}

// hasSmallOrder is used to check the if the Empherial key
// generated has small order or not
func hasSmallOrder(pubKey [32]byte) bool {
isSmallOrderPoint := false
for _, bl := range blacklist {
Expand All @@ -346,6 +350,9 @@ func hasSmallOrder(pubKey [32]byte) bool {
return isSmallOrderPoint
}

// Creates hash function according to challenge, generally the
// hash function created is encrypted with 256 bytes and here the
// last 32 bytes has been encrypted for the challenge
func deriveSecretAndChallenge(dhSecret *[32]byte, locIsLeast bool) (recvSecret, sendSecret *[aeadKeySize]byte, challenge *[32]byte) {
hash := sha256.New
hkdf := hkdf.New(hash, dhSecret[:], nil, []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN"))
Expand Down Expand Up @@ -418,6 +425,8 @@ type authSigMessage struct {
Sig []byte
}

// Used in MakeSecretConnection and used to share the
// Authentic Share
func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {

// Send our info and receive theirs in tandem.
Expand Down
Loading