Skip to content

Commit

Permalink
GenerateCircID
Browse files Browse the repository at this point in the history
  • Loading branch information
mmcloughlin committed Oct 9, 2017
1 parent 54cb51e commit 31e4b4b
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 2 deletions.
12 changes: 12 additions & 0 deletions circuit.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,24 @@ package pearl

import (
"crypto/cipher"
"encoding/binary"
"errors"
"sync"

"github.com/mmcloughlin/pearl/torcrypto"
)

// GenerateCircID generates a circuit ID with the given most significant bit.
func GenerateCircID(f CellFormat, msb uint32) CircID {
b := torcrypto.Rand(4)
x := binary.BigEndian.Uint32(b)
x = (x >> 1) | (msb << 31)
if f.CircIDLen() == 2 {
x >>= 16
}
return CircID(x)
}

type CircuitDirectionState struct {
digest []byte
cipher.Stream
Expand Down
24 changes: 24 additions & 0 deletions circuit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package pearl

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestGenerateCircID2(t *testing.T) {
f := CircID2Format{}
assert.Equal(t, CircID(0), GenerateCircID(f, 0)>>15)
assert.Equal(t, CircID(1), GenerateCircID(f, 1)>>15)
}

func TestGenerateCircID4(t *testing.T) {
f := CircID4Format{}
assert.Equal(t, CircID(0), GenerateCircID(f, 0)>>31)
assert.Equal(t, CircID(1), GenerateCircID(f, 1)>>31)
}

func TestGenerateCircID4Rand(t *testing.T) {
f := CircID4Format{}
assert.NotEqual(t, GenerateCircID(f, 0), GenerateCircID(f, 0))
}
14 changes: 14 additions & 0 deletions torcrypto/core.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Package torcrypto provides cryptographic functions useful in tor.
package torcrypto

import "crypto/rand"

// Rand generates n bytes of cryptographic random. Panics if the read fails.
func Rand(n int) []byte {
x := make([]byte, n)
_, err := rand.Read(x)
if err != nil {
panic(err)
}
return x
}
2 changes: 0 additions & 2 deletions torcrypto/doc.go

This file was deleted.

0 comments on commit 31e4b4b

Please sign in to comment.