leader.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. package main
  2. //#cgo CFLAGS: -fopenmp -O2
  3. //#cgo LDFLAGS: -lcrypto -lm -fopenmp
  4. //#include "../c/dpf.h"
  5. //#include "../c/okv.h"
  6. //#include "../c/dpf.c"
  7. //#include "../c/okv.c"
  8. import "C"
  9. //ssssssssssssssss
  10. import (
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/sha256"
  14. "crypto/tls"
  15. "crypto/x509"
  16. "crypto/x509/pkix"
  17. "encoding/pem"
  18. "fmt"
  19. "math"
  20. "math/big"
  21. mr "math/rand"
  22. "net"
  23. "sort"
  24. "strconv"
  25. "sync"
  26. "time"
  27. lib "2PPS/lib"
  28. "unsafe"
  29. "golang.org/x/crypto/nacl/box"
  30. )
  31. //this stores all neccessary information for each client
  32. type clientKeys struct {
  33. roundsParticipating int
  34. PublicKey *[32]byte
  35. SharedSecret [32]byte
  36. PirQuery [][]byte
  37. }
  38. var clientData = make(map[net.Addr]clientKeys)
  39. const follower string = "127.0.0.1:4442"
  40. var leaderPrivateKey *[32]byte
  41. var leaderPublicKey *[32]byte
  42. var followerPublicKey *[32]byte
  43. const maxNumberOfClients = 10000000
  44. var topicList []byte
  45. var topicAmount int
  46. var archiveTopicAmount int
  47. // every roundsBeforeUpdate the client updates his pirQuery
  48. const roundsBeforeUpdate = 5
  49. const neededSubscriptions = 1
  50. const numThreads = 12
  51. const dataLength = 64
  52. var dbWriteSize int = 4
  53. var maxTimePerRound time.Duration = 5 * time.Second
  54. //counts the number of rounds
  55. var round int = 1
  56. var startTime time.Time
  57. //channel for goroutine communication with clients
  58. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  59. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  60. //variables for calculating the dbWrite size
  61. const publisherRounds int = 3
  62. var publisherAmount float64
  63. var publisherHistory [publisherRounds]int
  64. //todo! handle client dc during phase1/3
  65. func main() {
  66. //prevents race conditions for wrtiting
  67. m := &sync.RWMutex{}
  68. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  69. if err != nil {
  70. panic(err)
  71. }
  72. //why is this neccessary?
  73. leaderPrivateKey = generatedPrivateKey
  74. leaderPublicKey = generatedPublicKey
  75. /*
  76. if len(os.Args) != 4 {
  77. fmt.Println("try again with: numThreads, dataLength, numRows")
  78. return
  79. }
  80. numThreads, _ = strconv.Atoi(os.Args[2])
  81. dataLength, _ = strconv.Atoi(os.Args[3])
  82. numRows, _ = strconv.Atoi(os.Args[4])
  83. */
  84. C.initializeServer(C.int(numThreads))
  85. //calls follower for setup
  86. conf := &tls.Config{
  87. InsecureSkipVerify: true,
  88. }
  89. followerConnection, err := tls.Dial("tcp", follower, conf)
  90. if err != nil {
  91. panic(err)
  92. }
  93. followerConnection.SetDeadline(time.Time{})
  94. //receives follower publicKey
  95. var tmpFollowerPubKey [32]byte
  96. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  97. if err != nil {
  98. panic(err)
  99. }
  100. followerPublicKey = &tmpFollowerPubKey
  101. //send publicKey to follower
  102. writeToConn(followerConnection, leaderPublicKey[:])
  103. //goroutine for accepting new clients
  104. go func() {
  105. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  106. if err != nil {
  107. panic(err)
  108. }
  109. // Generate a pem block with the private key
  110. keyPem := pem.EncodeToMemory(&pem.Block{
  111. Type: "RSA PRIVATE KEY",
  112. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  113. })
  114. tml := x509.Certificate{
  115. // you can add any attr that you need
  116. NotBefore: time.Now(),
  117. NotAfter: time.Now().AddDate(5, 0, 0),
  118. // you have to generate a different serial number each execution
  119. SerialNumber: big.NewInt(123123),
  120. Subject: pkix.Name{
  121. CommonName: "New Name",
  122. Organization: []string{"New Org."},
  123. },
  124. BasicConstraintsValid: true,
  125. }
  126. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  127. if err != nil {
  128. panic(err)
  129. }
  130. // Generate a pem block with the certificate
  131. certPem := pem.EncodeToMemory(&pem.Block{
  132. Type: "CERTIFICATE",
  133. Bytes: cert,
  134. })
  135. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  136. if err != nil {
  137. panic(err)
  138. }
  139. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  140. //listens for clients
  141. lnClients, err := tls.Listen("tcp", ":4441", config)
  142. if err != nil {
  143. panic(err)
  144. }
  145. defer lnClients.Close()
  146. for {
  147. clientConnection, err := lnClients.Accept()
  148. if err != nil {
  149. fmt.Println(err)
  150. }
  151. clientConnection.SetDeadline(time.Time{})
  152. //sends topicList so client can participate in phase 3 asap
  153. sendTopicLists(clientConnection)
  154. //send leader publicKey
  155. _, err = clientConnection.Write(leaderPublicKey[:])
  156. if err != nil {
  157. fmt.Println(err)
  158. clientConnection.Close()
  159. break
  160. }
  161. //send follower publicKey
  162. _, err = clientConnection.Write(followerPublicKey[:])
  163. if err != nil {
  164. fmt.Println(err)
  165. clientConnection.Close()
  166. break
  167. }
  168. var clientPublicKey *[32]byte
  169. var tmpClientPublicKey [32]byte
  170. //gets publicKey from client
  171. _, err = clientConnection.Read(tmpClientPublicKey[:])
  172. if err != nil {
  173. fmt.Println(err)
  174. clientConnection.Close()
  175. break
  176. }
  177. clientPublicKey = &tmpClientPublicKey
  178. //this is the key for map(client data)
  179. remoteAddress := clientConnection.RemoteAddr()
  180. //pirQuery will be added in phase 3
  181. //bs! only want to set roundsParticipating and answerAmount to 0, mb there is a better way
  182. //will work for now
  183. var emptyArray [32]byte
  184. var emptyByteArray [][]byte
  185. keys := clientKeys{0, clientPublicKey, emptyArray, emptyByteArray}
  186. m.Lock()
  187. clientData[remoteAddress] = keys
  188. m.Unlock()
  189. phase1Channel <- clientConnection
  190. }
  191. }()
  192. wg := &sync.WaitGroup{}
  193. //the current phase
  194. phase := make([]byte, 1)
  195. for {
  196. //phase1
  197. startTime = time.Now()
  198. phase[0] = 1
  199. fmt.Println("phase1")
  200. //creates a new write Db for this round
  201. for i := 0; i < dbWriteSize; i++ {
  202. C.createDb(C.int(1), C.int(dataLength))
  203. }
  204. //creates a new db containing virtual addresses for auditing
  205. virtualAddresses := createVirtualAddresses()
  206. //send all virtualAddresses to follower
  207. for i := 0; i <= dbWriteSize; i++ {
  208. writeToConn(followerConnection, intToByte(virtualAddresses[i]))
  209. }
  210. for id := 0; id < numThreads; id++ {
  211. wg.Add(1)
  212. followerConnection, err := tls.Dial("tcp", follower, conf)
  213. if err != nil {
  214. panic(err)
  215. }
  216. followerConnection.SetDeadline(time.Time{})
  217. go phase1(id, phase, followerConnection, wg, m, startTime, virtualAddresses)
  218. }
  219. wg.Wait()
  220. fmt.Println("phase2")
  221. //phase2
  222. followerConnection, err := tls.Dial("tcp", follower, conf)
  223. if err != nil {
  224. panic(err)
  225. }
  226. followerConnection.SetDeadline(time.Time{})
  227. phase2(followerConnection)
  228. //phase3
  229. fmt.Println("phase3")
  230. //no tweets -> continue to phase 1 and mb get tweets
  231. topicList, topicAmount = lib.GetTopicList(0)
  232. if len(topicList) == 0 {
  233. continue
  234. }
  235. phase[0] = 3
  236. startTime = time.Now()
  237. for id := 0; id < numThreads; id++ {
  238. wg.Add(1)
  239. followerConnection, err := tls.Dial("tcp", follower, conf)
  240. if err != nil {
  241. panic(err)
  242. }
  243. followerConnection.SetDeadline(time.Time{})
  244. go phase3(id, phase, followerConnection, wg, startTime, m)
  245. }
  246. wg.Wait()
  247. lib.CleanUpdbR(round)
  248. round++
  249. }
  250. }
  251. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, startTime time.Time, virtualAddresses []int) {
  252. roundAsBytes := intToByte(round)
  253. gotClient := make([]byte, 1)
  254. gotClient[0] = 0
  255. //wait until time is up
  256. for len(phase1Channel) == 0 {
  257. if time.Since(startTime) > maxTimePerRound {
  258. //tells follower that this worker is done
  259. writeToConn(followerConnection, gotClient)
  260. wg.Done()
  261. return
  262. }
  263. time.Sleep(1 * time.Second)
  264. }
  265. for clientConnection := range phase1Channel {
  266. gotClient[0] = 1
  267. //tells follower that this worker got a clientConnection
  268. writeToConn(followerConnection, gotClient)
  269. //sends clients publicKey to follower
  270. m.RLock()
  271. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  272. m.RUnlock()
  273. writeToConn(followerConnection, clientPublicKey[:])
  274. //setup the worker-specific db
  275. dbSize := int(C.dbSize)
  276. db := make([][]byte, dbSize)
  277. for i := 0; i < dbSize; i++ {
  278. db[i] = make([]byte, int(C.db[i].dataSize))
  279. }
  280. //tells client that phase 1 has begun
  281. writeToConn(clientConnection, phase)
  282. //tells client current dbWriteSize
  283. writeToConn(clientConnection, intToByte(dbWriteSize))
  284. //tells client current round
  285. writeToConn(clientConnection, roundAsBytes)
  286. m.RLock()
  287. var clientKeys = clientData[clientConnection.RemoteAddr()]
  288. m.RUnlock()
  289. clientKeys, pirQuery := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  290. getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  291. m.Lock()
  292. clientData[clientConnection.RemoteAddr()] = clientKeys
  293. m.Unlock()
  294. //accept dpfQuery from client
  295. dpfLengthBytes := make([]byte, 4)
  296. dpfLengthBytes = readFromConn(clientConnection, 4)
  297. dpfLength := byteToInt(dpfLengthBytes)
  298. dpfQueryAEncrypted := make([]byte, dpfLength)
  299. dpfQueryBEncrypted := make([]byte, dpfLength)
  300. dpfQueryAEncrypted = readFromConn(clientConnection, dpfLength)
  301. dpfQueryBEncrypted = readFromConn(clientConnection, dpfLength)
  302. writeToConn(followerConnection, dpfLengthBytes)
  303. writeToConn(followerConnection, dpfQueryBEncrypted)
  304. //decrypt dpfQueryA for sorting into db
  305. var decryptNonce [24]byte
  306. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  307. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  308. if !ok {
  309. panic("dpfQueryA decryption not ok")
  310. }
  311. ds := int(C.db[0].dataSize)
  312. dataShareLeader := make([]byte, ds)
  313. pos := C.getUint128_t(C.int(virtualAddresses[dbWriteSize]))
  314. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  315. dataShareFollower := make([]byte, ds)
  316. dataShareFollower = readFromConn(followerConnection, ds)
  317. writeToConn(followerConnection, dataShareLeader)
  318. auditXOR := make([]byte, ds)
  319. passedAudit := true
  320. for i := 0; i < ds; i++ {
  321. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  322. //client tried to write to a position that is not a virtuallAddress
  323. if auditXOR[i] != 0 {
  324. clientConnection.Close()
  325. passedAudit = false
  326. }
  327. }
  328. if passedAudit {
  329. //run dpf, xor into local db
  330. for i := 0; i < dbSize; i++ {
  331. ds := int(C.db[i].dataSize)
  332. dataShare := make([]byte, ds)
  333. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  334. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  335. for j := 0; j < ds; j++ {
  336. db[i][j] = db[i][j] ^ dataShare[j]
  337. }
  338. }
  339. //xor the worker's DB into the main DB
  340. for i := 0; i < dbSize; i++ {
  341. m.Lock()
  342. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  343. m.Unlock()
  344. }
  345. phase3Channel <- clientConnection
  346. }
  347. //loop that waits for new client or leaves phase1 if time is up
  348. for {
  349. if time.Since(startTime) < maxTimePerRound {
  350. //this worker handles the next client
  351. if len(phase1Channel) > 0 {
  352. break
  353. //this worker waits for next client
  354. } else {
  355. time.Sleep(1 * time.Second)
  356. }
  357. //times up
  358. } else {
  359. //tells follower that this worker is done
  360. gotClient[0] = 0
  361. writeToConn(followerConnection, gotClient)
  362. wg.Done()
  363. return
  364. }
  365. }
  366. }
  367. }
  368. func phase2(followerConnection net.Conn) {
  369. //gets current seed
  370. seedLeader := make([]byte, 16)
  371. C.readSeed((*C.uchar)(&seedLeader[0]))
  372. //get data
  373. dbSize := int(C.dbSize)
  374. tmpdbLeader := make([][]byte, dbSize)
  375. for i := range tmpdbLeader {
  376. tmpdbLeader[i] = make([]byte, dataLength)
  377. }
  378. for i := 0; i < dbSize; i++ {
  379. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  380. }
  381. //writes seed to follower
  382. writeToConn(followerConnection, seedLeader)
  383. //write data to follower
  384. //this is surely inefficent
  385. for i := 0; i < dbSize; i++ {
  386. writeToConn(followerConnection, tmpdbLeader[i])
  387. }
  388. //receive seed from follower
  389. seedFollower := make([]byte, 16)
  390. seedFollower = readFromConn(followerConnection, 16)
  391. //receive data from follower
  392. tmpdbFollower := make([][]byte, dbSize)
  393. for i := range tmpdbFollower {
  394. tmpdbFollower[i] = make([]byte, dataLength)
  395. }
  396. for i := 0; i < dbSize; i++ {
  397. tmpdbFollower[i] = readFromConn(followerConnection, dataLength)
  398. }
  399. //put together the db
  400. tmpdb := make([][]byte, dbSize)
  401. for i := range tmpdb {
  402. tmpdb[i] = make([]byte, dataLength)
  403. }
  404. //get own Ciphers
  405. ciphersLeader := make([]*C.uchar, dbSize)
  406. for i := 0; i < dbSize; i++ {
  407. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  408. }
  409. for i := 0; i < dbSize; i++ {
  410. C.getCipher(1, C.int(i), ciphersLeader[i])
  411. }
  412. //send own Ciphers to follower
  413. for i := 0; i < dbSize; i++ {
  414. writeToConn(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  415. }
  416. //receive ciphers from follower
  417. ciphersFollower := make([]byte, dbSize*16)
  418. for i := 0; i < dbSize; i++ {
  419. _, err := followerConnection.Read(ciphersFollower[i*16:])
  420. if err != nil {
  421. panic(err)
  422. }
  423. }
  424. //put in ciphers from follower
  425. for i := 0; i < dbSize; i++ {
  426. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  427. }
  428. //decrypt each row
  429. for i := 0; i < dbSize; i++ {
  430. C.decryptRow(C.int(i), (*C.uchar)(&tmpdb[i][0]), (*C.uchar)(&tmpdbLeader[i][0]), (*C.uchar)(&tmpdbFollower[i][0]), (*C.uchar)(&seedLeader[0]), (*C.uchar)(&seedFollower[0]))
  431. }
  432. var tweets []lib.Tweet
  433. var currentPublisherAmount int = 0
  434. for i := 0; i < dbSize; i++ {
  435. //discard cover message
  436. if tmpdb[i][0] == 0 {
  437. continue
  438. } else {
  439. currentPublisherAmount++
  440. //reconstruct tweet
  441. var position int = 0
  442. var topics []string
  443. var topic string
  444. var text string
  445. for _, letter := range tmpdb[i] {
  446. if string(letter) == ";" {
  447. if topic != "" {
  448. topics = append(topics, topic)
  449. topic = ""
  450. }
  451. position++
  452. } else {
  453. if position == 0 {
  454. if string(letter) == "," {
  455. topics = append(topics, topic)
  456. topic = ""
  457. } else {
  458. topic = topic + string(letter)
  459. }
  460. } else if position == 1 {
  461. text = text + string(letter)
  462. }
  463. }
  464. }
  465. tweet := lib.Tweet{"", -1, topics, text, round}
  466. tweets = append(tweets, tweet)
  467. }
  468. }
  469. //fmt.Println("tweets recovered: ", tweets)
  470. //sort into read db
  471. lib.NewEntries(tweets, 0)
  472. C.resetDb()
  473. //calculates the publisherAverage over the last publisherRounds rounds
  474. index := round % publisherRounds
  475. publisherHistory[index] = currentPublisherAmount
  476. var publisherAmount int
  477. for _, num := range publisherHistory {
  478. publisherAmount += num
  479. }
  480. publisherAverage := 0
  481. if round < publisherRounds {
  482. publisherAverage = publisherAmount / round
  483. } else {
  484. publisherAverage = publisherAmount / publisherRounds
  485. }
  486. //calculates the dbWriteSize for this round
  487. dbWriteSize = int(math.Ceil(19.5 * float64(publisherAverage)))
  488. //writes dbWriteSize of current round to follower
  489. writeToConn(followerConnection, intToByte(dbWriteSize))
  490. }
  491. func addTestTweets() {
  492. //creates test tweets
  493. tweets := make([]lib.Tweet, 5)
  494. for i := range tweets {
  495. j := i
  496. if i == 1 {
  497. j = 0
  498. }
  499. text := "Text " + strconv.Itoa(i)
  500. var topics []string
  501. topics = append(topics, "Topic "+strconv.Itoa(j))
  502. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  503. }
  504. lib.NewEntries(tweets, 0)
  505. }
  506. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  507. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, startTime time.Time, m *sync.RWMutex) {
  508. gotClient := make([]byte, 1)
  509. gotClient[0] = 0
  510. //wait until time is up
  511. for len(phase3Channel) == 0 {
  512. if time.Since(startTime) > maxTimePerRound {
  513. //tells follower that this worker is done
  514. writeToConn(followerConnection, gotClient)
  515. wg.Done()
  516. return
  517. }
  518. time.Sleep(1 * time.Second)
  519. }
  520. for clientConnection := range phase3Channel {
  521. gotClient[0] = 1
  522. //tells follower that this worker got a clientConnection
  523. writeToConn(followerConnection, gotClient)
  524. //tells client current phase
  525. writeToConn(clientConnection, phase)
  526. /*
  527. possible Values
  528. 0 : new client
  529. leader expects sharedSecrets, expects pirQuery
  530. 1 : update needed
  531. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  532. 2 : no update needed
  533. nothing
  534. */
  535. subPhase := make([]byte, 1)
  536. //gets the data for the current client
  537. m.RLock()
  538. var clientKeys = clientData[clientConnection.RemoteAddr()]
  539. m.RUnlock()
  540. var roundsParticipating = clientKeys.roundsParticipating
  541. //client participates for the first time
  542. if roundsParticipating == 0 {
  543. subPhase[0] = 0
  544. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  545. subPhase[0] = 1
  546. } else {
  547. subPhase[0] = 2
  548. }
  549. //tells client what leader expects
  550. writeToConn(clientConnection, subPhase)
  551. //tells follower what will happen
  552. writeToConn(followerConnection, subPhase)
  553. //sends clients publicKey so follower knows which client is being served
  554. writeToConn(followerConnection, clientKeys.PublicKey[:])
  555. //increases rounds participating for client
  556. clientKeys.roundsParticipating = roundsParticipating + 1
  557. //declaring variables here to prevent dupclicates later
  558. m.RLock()
  559. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  560. m.RUnlock()
  561. if subPhase[0] == 0 {
  562. sendTopicLists(clientConnection)
  563. clientKeys, _ = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  564. } else if subPhase[0] == 1 {
  565. sendTopicLists(clientConnection)
  566. //updates sharedSecret
  567. sharedSecret = sha256.Sum256(sharedSecret[:])
  568. clientKeys.SharedSecret = sharedSecret
  569. clientKeys, _ = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  570. }
  571. getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  572. wantsArchive := make([]byte, 1)
  573. wantsArchive = readFromConn(clientConnection, 1)
  574. writeToConn(followerConnection, wantsArchive)
  575. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  576. _, archiveQuerys := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  577. getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  578. }
  579. //saves all changes for client
  580. m.Lock()
  581. clientData[clientConnection.RemoteAddr()] = clientKeys
  582. m.Unlock()
  583. phase1Channel <- clientConnection
  584. for {
  585. if time.Since(startTime) < maxTimePerRound {
  586. //this worker handles the next client
  587. if len(phase3Channel) > 0 {
  588. break
  589. //this worker waits for next client
  590. } else {
  591. time.Sleep(1 * time.Second)
  592. }
  593. //times up
  594. } else {
  595. //tells follower that this worker is done
  596. gotClient[0] = 0
  597. writeToConn(followerConnection, gotClient)
  598. wg.Done()
  599. return
  600. }
  601. }
  602. }
  603. }
  604. func createVirtualAddresses() []int {
  605. //array will be filled with unique random ascending values
  606. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  607. //+1 to have a position to evaluate each received message
  608. arraySize := dbWriteSize + 1
  609. var maxInt int = int(math.Pow(2, 31))
  610. virtualAddresses := make([]int, arraySize)
  611. for i := 0; i < arraySize; i++ {
  612. virtualAddresses[i] = mr.Intn(maxInt)
  613. for j := 0; j < i; j++ {
  614. if virtualAddresses[i] == virtualAddresses[j] {
  615. i--
  616. break
  617. }
  618. }
  619. }
  620. sort.Ints(virtualAddresses)
  621. return virtualAddresses
  622. }
  623. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) {
  624. //xores all requested addresses into virtuallAddress
  625. virtualAddress := make([]byte, 4)
  626. for index, num := range pirQuery {
  627. if num == 1 {
  628. currentAddress := intToByte(virtualAddresses[index])
  629. for i := 0; i < 4; i++ {
  630. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  631. }
  632. }
  633. }
  634. //xores the sharedSecret
  635. for i := 0; i < 4; i++ {
  636. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  637. }
  638. virtualAddressFollower := make([]byte, 4)
  639. virtualAddressFollower = readFromConn(followerConnection, 4)
  640. //xores the data from follower
  641. for i := 0; i < 4; i++ {
  642. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  643. }
  644. writeToConn(clientConnection, virtualAddress)
  645. }
  646. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) {
  647. tmpNeededSubscriptions := neededSubscriptions
  648. if archiveQuerys != nil {
  649. tmpNeededSubscriptions = len(archiveQuerys)
  650. }
  651. for i := 0; i < tmpNeededSubscriptions; i++ {
  652. //gets all requested tweets
  653. var tweets []byte
  654. if archiveQuerys == nil {
  655. tweets = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0)
  656. } else {
  657. tweets = lib.GetTweets(archiveQuerys[i], dataLength, 1)
  658. }
  659. //expand sharedSecret so it is of right length
  660. expandBy := len(tweets) / 32
  661. var expandedSharedSecret []byte
  662. for i := 0; i < expandBy; i++ {
  663. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  664. }
  665. //Xor's sharedSecret with all tweets
  666. lib.Xor(expandedSharedSecret[:], tweets)
  667. //receives tweets from follower and Xor's them in
  668. tweetsLengthBytes := make([]byte, 4)
  669. tweetsLengthBytes = readFromConn(followerConnection, 4)
  670. tweetsReceivedLength := byteToInt(tweetsLengthBytes)
  671. receivedTweets := make([]byte, tweetsReceivedLength)
  672. receivedTweets = readFromConn(followerConnection, tweetsReceivedLength)
  673. lib.Xor(receivedTweets, tweets)
  674. //sends tweets to client
  675. tweetsLengthBytes = intToByte(len(tweets))
  676. writeToConn(clientConnection, tweetsLengthBytes)
  677. writeToConn(clientConnection, tweets)
  678. }
  679. }
  680. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte) {
  681. clientPublicKey := clientKeys.PublicKey
  682. //gets the msg length
  683. msgLengthBytes := make([]byte, 4)
  684. msgLengthBytes = readFromConn(clientConnection, 4)
  685. msgLength := byteToInt(msgLengthBytes)
  686. leaderBox := make([]byte, msgLength)
  687. followerBox := make([]byte, msgLength)
  688. //gets the leader box
  689. leaderBox = readFromConn(clientConnection, msgLength)
  690. //gets the follower box
  691. followerBox = readFromConn(clientConnection, msgLength)
  692. tmpNeededSubscriptions := neededSubscriptions
  693. tmpTopicAmount := topicAmount
  694. if subPhase == -1 {
  695. archiveNeededSubscriptions := make([]byte, 4)
  696. archiveNeededSubscriptions = readFromConn(clientConnection, 4)
  697. writeToConn(followerConnection, archiveNeededSubscriptions)
  698. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  699. tmpTopicAmount = archiveTopicAmount
  700. }
  701. if doAuditing {
  702. tmpNeededSubscriptions = 1
  703. tmpTopicAmount = dbWriteSize
  704. }
  705. //send length to follower
  706. writeToConn(followerConnection, msgLengthBytes)
  707. //send box to follower
  708. writeToConn(followerConnection, followerBox)
  709. var decryptNonce [24]byte
  710. copy(decryptNonce[:], leaderBox[:24])
  711. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  712. if !ok {
  713. panic("pirQuery decryption not ok")
  714. }
  715. //if sharedSecret is send
  716. if subPhase == 0 {
  717. var tmpSharedSecret [32]byte
  718. for index := 0; index < 32; index++ {
  719. tmpSharedSecret[index] = decrypted[index]
  720. }
  721. clientKeys.SharedSecret = tmpSharedSecret
  722. decrypted = decrypted[32:]
  723. }
  724. if doAuditing {
  725. result := make([][]byte, 1)
  726. result[0] = decrypted
  727. return clientKeys, result
  728. }
  729. //transforms byteArray to ints of wanted topics
  730. pirQueryFlattened := decrypted
  731. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  732. for i := range pirQuerys {
  733. pirQuerys[i] = make([]byte, tmpTopicAmount)
  734. }
  735. for i := 0; i < tmpNeededSubscriptions; i++ {
  736. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  737. }
  738. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  739. if subPhase != -1 {
  740. clientKeys.PirQuery = pirQuerys
  741. }
  742. return clientKeys, pirQuerys
  743. }
  744. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  745. var topics []string
  746. var topic string
  747. var position int = 0
  748. for _, letter := range topicsAsBytes {
  749. if string(letter) == "," {
  750. topics[position] = topic
  751. topic = ""
  752. position++
  753. } else {
  754. topic = topic + string(letter)
  755. }
  756. }
  757. return topics
  758. }
  759. func byteToInt(myBytes []byte) (x int) {
  760. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  761. return
  762. }
  763. func sendTopicLists(clientConnection net.Conn) {
  764. for i := 0; i < 2; i++ {
  765. var topicList []byte
  766. if i == 0 {
  767. topicList, topicAmount = lib.GetTopicList(i)
  768. } else {
  769. topicList, archiveTopicAmount = lib.GetTopicList(i)
  770. }
  771. topicListLengthBytes := intToByte(len(topicList))
  772. writeToConn(clientConnection, topicListLengthBytes)
  773. writeToConn(clientConnection, topicList)
  774. }
  775. }
  776. //sends the array to the connection
  777. func writeToConn(connection net.Conn, array []byte) {
  778. _, err := connection.Write(array)
  779. if err != nil {
  780. panic(err)
  781. }
  782. }
  783. //reads an array which is returned and of size "size" from the connection
  784. func readFromConn(connection net.Conn, size int) []byte {
  785. array := make([]byte, size)
  786. _, err := connection.Read(array)
  787. if err != nil {
  788. panic(err)
  789. }
  790. return array
  791. }
  792. func intToByte(myInt int) (retBytes []byte) {
  793. retBytes = make([]byte, 4)
  794. retBytes[3] = byte((myInt >> 24) & 0xff)
  795. retBytes[2] = byte((myInt >> 16) & 0xff)
  796. retBytes[1] = byte((myInt >> 8) & 0xff)
  797. retBytes[0] = byte(myInt & 0xff)
  798. return
  799. }