Adding RandNumber util to simplify chatchannel logic

This commit is contained in:
Sarah Jamie Lewis 2018-01-12 13:02:15 -05:00
parent 30808c71b2
commit 4ccf95bee0
4 changed files with 22 additions and 11 deletions

View File

@ -1,13 +1,10 @@
package channels
import (
"crypto/rand"
"github.com/golang/protobuf/proto"
"github.com/s-rah/go-ricochet/utils"
"github.com/s-rah/go-ricochet/wire/chat"
"github.com/s-rah/go-ricochet/wire/control"
"math"
"math/big"
"time"
)
@ -100,10 +97,7 @@ func (cc *ChatChannel) RequiresAuthentication() string {
// returned, it will be sent as the ChannelResult message.
func (cc *ChatChannel) OpenInbound(channel *Channel, raw *Protocol_Data_Control.OpenChannel) ([]byte, error) {
cc.channel = channel
id, err := rand.Int(rand.Reader, big.NewInt(math.MaxUint32))
if err != nil {
return nil, err
}
id := utils.GetRandNumber()
cc.lastMessageID = uint32(id.Uint64())
cc.channel.Pending = false
messageBuilder := new(utils.MessageBuilder)
@ -115,10 +109,7 @@ func (cc *ChatChannel) OpenInbound(channel *Channel, raw *Protocol_Data_Control.
// returned, it will be sent as the OpenChannel message.
func (cc *ChatChannel) OpenOutbound(channel *Channel) ([]byte, error) {
cc.channel = channel
id, err := rand.Int(rand.Reader, big.NewInt(math.MaxUint32))
if err != nil {
return nil, err
}
id := utils.GetRandNumber()
cc.lastMessageID = uint32(id.Uint64())
messageBuilder := new(utils.MessageBuilder)
return messageBuilder.OpenChannel(channel.ID, cc.Type()), nil

View File

@ -120,5 +120,7 @@ func TestChatChannelOperations(t *testing.T) {
chatChannel.Packet(chat)
chatChannel.SendMessage("hello")
ackMessage := messageBuilder.AckChatMessage(0, true)
chatChannel.Packet(ackMessage)
}

View File

@ -7,6 +7,8 @@ import (
"encoding/pem"
"errors"
"io/ioutil"
"math"
"math/big"
)
const (
@ -17,6 +19,14 @@ const (
RicochetKeySize = 1024
)
func GetRandNumber() *big.Int {
num, err := rand.Int(rand.Reader, big.NewInt(math.MaxUint32))
// If we can't generate random numbers then panicking is probably
// the best option.
CheckError(err)
return num
}
// GeneratePrivateKey generates a new private key for use
func GeneratePrivateKey() (*rsa.PrivateKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, RicochetKeySize)

View File

@ -2,6 +2,7 @@ package utils
import (
"testing"
"math"
)
func TestGeneratePrivateKey(t *testing.T) {
@ -17,3 +18,10 @@ func TestLoadPrivateKey(t *testing.T) {
t.Errorf("Error while loading private key from file: %v", err)
}
}
func TestGetRandNumber(t *testing.T) {
num := GetRandNumber()
if !num.IsUint64() || num.Uint64() > uint64(math.MaxUint32) {
t.Errorf("Error random number outside of expected bounds %v", num)
}
}