summaryrefslogtreecommitdiffhomepage
path: root/src/index.go
diff options
context:
space:
mode:
authorMathias Hall-Andersen <mathias@hall-andersen.dk>2017-06-24 15:34:17 +0200
committerMathias Hall-Andersen <mathias@hall-andersen.dk>2017-06-24 15:34:44 +0200
commit25190e43369a79dc77a740dc8cd28b8a9fcb235e (patch)
treeb7057627e0710fe9ef40c077a204904c78bed9cc /src/index.go
parent521e77fd54fba275405affd790ac91f7998e4559 (diff)
Restructuring of noise impl.
Diffstat (limited to 'src/index.go')
-rw-r--r--src/index.go82
1 files changed, 82 insertions, 0 deletions
diff --git a/src/index.go b/src/index.go
new file mode 100644
index 0000000..83a7e29
--- /dev/null
+++ b/src/index.go
@@ -0,0 +1,82 @@
+package main
+
+import (
+ "crypto/rand"
+ "sync"
+)
+
+/* Index=0 is reserved for unset indecies
+ *
+ */
+
+type IndexTable struct {
+ mutex sync.RWMutex
+ keypairs map[uint32]*KeyPair
+ handshakes map[uint32]*Handshake
+}
+
+func randUint32() (uint32, error) {
+ var buff [4]byte
+ _, err := rand.Read(buff[:])
+ id := uint32(buff[0])
+ id <<= 8
+ id |= uint32(buff[1])
+ id <<= 8
+ id |= uint32(buff[2])
+ id <<= 8
+ id |= uint32(buff[3])
+ return id, err
+}
+
+func (table *IndexTable) Init() {
+ table.mutex.Lock()
+ defer table.mutex.Unlock()
+ table.keypairs = make(map[uint32]*KeyPair)
+ table.handshakes = make(map[uint32]*Handshake)
+}
+
+func (table *IndexTable) NewIndex(handshake *Handshake) (uint32, error) {
+ table.mutex.Lock()
+ defer table.mutex.Unlock()
+ for {
+ // generate random index
+
+ id, err := randUint32()
+ if err != nil {
+ return id, err
+ }
+ if id == 0 {
+ continue
+ }
+
+ // check if index used
+
+ _, ok := table.keypairs[id]
+ if ok {
+ continue
+ }
+ _, ok = table.handshakes[id]
+ if ok {
+ continue
+ }
+
+ // update the index
+
+ delete(table.handshakes, handshake.localIndex)
+ handshake.localIndex = id
+ table.handshakes[id] = handshake
+ return id, nil
+ }
+}
+
+func (table *IndexTable) LookupKeyPair(id uint32) *KeyPair {
+ table.mutex.RLock()
+ defer table.mutex.RUnlock()
+ return table.keypairs[id]
+}
+
+func (table *IndexTable) LookupHandshake(id uint32) *Handshake {
+ table.mutex.RLock()
+ defer table.mutex.RUnlock()
+ return table.handshakes[id]
+}