leader.go 25 KB

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