leader.go 23 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. "net"
  22. "strconv"
  23. "sync"
  24. "time"
  25. lib "2PPS/lib"
  26. "unsafe"
  27. "golang.org/x/crypto/nacl/box"
  28. )
  29. //this stores all neccessary information for each client
  30. type clientKeys struct {
  31. roundsParticipating int
  32. PublicKey *[32]byte
  33. SharedSecret [32]byte
  34. PirQuery [][]byte
  35. }
  36. var clientData = make(map[net.Addr]clientKeys)
  37. var leaderPrivateKey *[32]byte
  38. var leaderPublicKey *[32]byte
  39. var followerPublicKey *[32]byte
  40. // every roundsBeforeUpdate the client updates his pirQuery, the sharedSecrets are updated locally
  41. const roundsBeforeUpdate int = 1
  42. const follower string = "127.0.0.1:4443"
  43. const maxNumberOfClients = 1000
  44. //needs to be changed at leader/follower/client at the same time
  45. const neededSubscriptions = 1
  46. var topicList []byte
  47. var topicAmount int
  48. var archiveTopicAmount int
  49. //works on my machine
  50. var numThreads = 12
  51. //has to be dividable by 32
  52. var dataLength int = 32
  53. //this needs to be adjusted peridodically
  54. var dbWriteSize int = 2
  55. //counts the number of rounds
  56. var round int = 1
  57. var startTime time.Time
  58. //adjust this for follower aswell
  59. var maxTimePerRound time.Duration = 5 * time.Second
  60. //channel for goroutine communication with clients
  61. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  62. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  63. //variables for calculating the dbWrite size
  64. const publisherRounds int = 3
  65. var publisherAmount float64
  66. var publisherHistory [publisherRounds]int
  67. func main() {
  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. _, err = followerConnection.Write(leaderPublicKey[:])
  103. if err != nil {
  104. panic(err)
  105. }
  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. for id := 0; id < numThreads; id++ {
  208. wg.Add(1)
  209. followerConnection, err := tls.Dial("tcp", follower, conf)
  210. if err != nil {
  211. panic(err)
  212. }
  213. followerConnection.SetDeadline(time.Time{})
  214. go phase1(id, phase, followerConnection, wg, m, startTime)
  215. }
  216. wg.Wait()
  217. fmt.Println("phase2")
  218. //phase2
  219. followerConnection, err := tls.Dial("tcp", follower, conf)
  220. if err != nil {
  221. panic(err)
  222. }
  223. followerConnection.SetDeadline(time.Time{})
  224. phase2(followerConnection)
  225. //phase3
  226. fmt.Println("phase3")
  227. //no tweets -> continue to phase 1 and mb get tweets
  228. topicList, topicAmount = lib.GetTopicList(0)
  229. if len(topicList) == 0 {
  230. continue
  231. }
  232. phase[0] = 3
  233. startTime = time.Now()
  234. for id := 0; id < numThreads; id++ {
  235. wg.Add(1)
  236. followerConnection, err := tls.Dial("tcp", follower, conf)
  237. if err != nil {
  238. panic(err)
  239. }
  240. followerConnection.SetDeadline(time.Time{})
  241. go phase3(id, phase, followerConnection, wg, startTime)
  242. }
  243. wg.Wait()
  244. lib.CleanUpdbR(round)
  245. round++
  246. }
  247. }
  248. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m sync.Mutex, startTime time.Time) {
  249. roundAsBytes := intToByte(round)
  250. gotClient := make([]byte, 1)
  251. gotClient[0] = 0
  252. //wait until time is up
  253. for len(phase1Channel) == 0 {
  254. if time.Since(startTime) > maxTimePerRound {
  255. //tells follower that this worker is done
  256. _, err := followerConnection.Write(gotClient)
  257. if err != nil {
  258. panic(err)
  259. }
  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. _, err := followerConnection.Write(gotClient)
  269. if err != nil {
  270. panic(err)
  271. }
  272. //sends clients publicKey to follower
  273. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  274. _, err = followerConnection.Write(clientPublicKey[:])
  275. if err != nil {
  276. panic(err)
  277. }
  278. //setup the worker-specific db
  279. dbSize := int(C.dbSize)
  280. db := make([][]byte, dbSize)
  281. for i := 0; i < dbSize; i++ {
  282. db[i] = make([]byte, int(C.db[i].dataSize))
  283. }
  284. //tells client that phase 1 has begun
  285. _, err = clientConnection.Write(phase)
  286. if err != nil {
  287. panic(err)
  288. }
  289. //tells client current dbWriteSize
  290. _, err = clientConnection.Write(intToByte(dbWriteSize))
  291. if err != nil {
  292. panic(err)
  293. }
  294. //tells client current round
  295. _, err = clientConnection.Write(roundAsBytes)
  296. if err != nil {
  297. panic(err)
  298. }
  299. //accept dpfQuery from client
  300. dpfLengthBytes := make([]byte, 4)
  301. _, err = clientConnection.Read(dpfLengthBytes)
  302. if err != nil {
  303. panic(err)
  304. }
  305. dpfLength := byteToInt(dpfLengthBytes)
  306. dpfQueryAEncrypted := make([]byte, dpfLength)
  307. dpfQueryBEncrypted := make([]byte, dpfLength)
  308. _, err = clientConnection.Read(dpfQueryAEncrypted)
  309. if err != nil {
  310. panic(err)
  311. }
  312. _, err = clientConnection.Read(dpfQueryBEncrypted)
  313. if err != nil {
  314. panic(err)
  315. }
  316. _, err = followerConnection.Write(dpfLengthBytes)
  317. if err != nil {
  318. panic(err)
  319. }
  320. _, err = followerConnection.Write(dpfQueryBEncrypted)
  321. if err != nil {
  322. panic(err)
  323. }
  324. //decrypt dpfQueryA for sorting into db
  325. var decryptNonce [24]byte
  326. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  327. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  328. if !ok {
  329. panic("dpfQueryA decryption not ok")
  330. }
  331. vector := make([]byte, dbSize*16)
  332. //var str string
  333. //run dpf, xor into local db
  334. for i := 0; i < dbSize; i++ {
  335. ds := int(C.db[i].dataSize)
  336. dataShare := make([]byte, ds)
  337. pos := C.getUint128_t(C.int(i))
  338. v := C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  339. copy(vector[i*16:(i+1)*16], C.GoBytes(unsafe.Pointer(&v), 16))
  340. for j := 0; j < ds; j++ {
  341. db[i][j] = db[i][j] ^ dataShare[j]
  342. }
  343. }
  344. //xor the worker's DB into the main DB
  345. for i := 0; i < dbSize; i++ {
  346. m.Lock()
  347. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  348. m.Unlock()
  349. }
  350. phase3Channel <- clientConnection
  351. //loop that waits for new client or leaves phase1 if time is up
  352. for {
  353. if time.Since(startTime) < maxTimePerRound {
  354. //this worker handles the next client
  355. if len(phase1Channel) > 0 {
  356. break
  357. //this worker waits for next client
  358. } else {
  359. time.Sleep(1 * time.Second)
  360. }
  361. //times up
  362. } else {
  363. //tells follower that this worker is done
  364. gotClient[0] = 0
  365. _, err := followerConnection.Write(gotClient)
  366. if err != nil {
  367. panic(err)
  368. }
  369. wg.Done()
  370. return
  371. }
  372. }
  373. }
  374. }
  375. func phase2(followerConnection net.Conn) {
  376. //gets current seed
  377. seedLeader := make([]byte, 16)
  378. C.readSeed((*C.uchar)(&seedLeader[0]))
  379. //get data
  380. dbSize := int(C.dbSize)
  381. tmpdbLeader := make([][]byte, dbSize)
  382. for i := range tmpdbLeader {
  383. tmpdbLeader[i] = make([]byte, dataLength)
  384. }
  385. for i := 0; i < dbSize; i++ {
  386. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  387. }
  388. //writes seed to follower
  389. _, err := followerConnection.Write(seedLeader)
  390. if err != nil {
  391. panic(err)
  392. }
  393. //write data to follower
  394. //this is surely inefficent
  395. for i := 0; i < dbSize; i++ {
  396. _, err = followerConnection.Write(tmpdbLeader[i])
  397. if err != nil {
  398. panic(err)
  399. }
  400. }
  401. //receive seed from follower
  402. seedFollower := make([]byte, 16)
  403. _, err = followerConnection.Read(seedFollower)
  404. if err != nil {
  405. panic(err)
  406. }
  407. //receive data from follower
  408. tmpdbFollower := make([][]byte, dbSize)
  409. for i := range tmpdbFollower {
  410. tmpdbFollower[i] = make([]byte, dataLength)
  411. }
  412. for i := 0; i < dbSize; i++ {
  413. _, err = followerConnection.Read(tmpdbFollower[i])
  414. if err != nil {
  415. panic(err)
  416. }
  417. }
  418. //put together the db
  419. tmpdb := make([][]byte, dbSize)
  420. for i := range tmpdb {
  421. tmpdb[i] = make([]byte, dataLength)
  422. }
  423. //get own Ciphers
  424. ciphersLeader := make([]*C.uchar, dbSize)
  425. for i := 0; i < dbSize; i++ {
  426. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  427. }
  428. for i := 0; i < dbSize; i++ {
  429. C.getCipher(1, C.int(i), ciphersLeader[i])
  430. }
  431. //send own Ciphers to follower
  432. for i := 0; i < dbSize; i++ {
  433. _, err = followerConnection.Write(C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  434. if err != nil {
  435. panic(err)
  436. }
  437. }
  438. //receive ciphers from follower
  439. ciphersFollower := make([]byte, dbSize*16)
  440. for i := 0; i < dbSize; i++ {
  441. _, err = followerConnection.Read(ciphersFollower[i*16:])
  442. if err != nil {
  443. panic(err)
  444. }
  445. }
  446. //put in ciphers from follower
  447. for i := 0; i < dbSize; i++ {
  448. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  449. }
  450. //decrypt each row
  451. for i := 0; i < dbSize; i++ {
  452. 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]))
  453. }
  454. var tweets []lib.Tweet
  455. var currentPublisherAmount int = 0
  456. for i := 0; i < dbSize; i++ {
  457. //discard cover message
  458. if tmpdb[i][0] == 0 {
  459. continue
  460. } else {
  461. currentPublisherAmount++
  462. //reconstruct tweet
  463. var position int = 0
  464. var topics []string
  465. var topic string
  466. var text string
  467. for _, letter := range tmpdb[i] {
  468. if string(letter) == ";" {
  469. if topic != "" {
  470. topics = append(topics, topic)
  471. topic = ""
  472. }
  473. position++
  474. } else {
  475. if position == 0 {
  476. if string(letter) == "," {
  477. topics = append(topics, topic)
  478. topic = ""
  479. } else {
  480. topic = topic + string(letter)
  481. }
  482. } else if position == 1 {
  483. text = text + string(letter)
  484. }
  485. }
  486. }
  487. tweet := lib.Tweet{"", -1, topics, text, round}
  488. tweets = append(tweets, tweet)
  489. }
  490. }
  491. //fmt.Println("tweets recovered: ", tweets)
  492. //sort into read db
  493. lib.NewEntries(tweets, 0)
  494. C.resetDb()
  495. //calculates the publisherAverage over the last publisherRounds rounds
  496. index := round % publisherRounds
  497. publisherHistory[index] = currentPublisherAmount
  498. var publisherAmount int
  499. for _, num := range publisherHistory {
  500. publisherAmount += num
  501. }
  502. publisherAverage := 0
  503. if round < publisherRounds {
  504. publisherAverage = publisherAmount / round
  505. } else {
  506. publisherAverage = publisherAmount / publisherRounds
  507. }
  508. //calculates the dbWriteSize for this round
  509. dbWriteSize = int(math.Ceil(19.5 * float64(publisherAverage)))
  510. //writes dbWriteSize of current round to follower
  511. _, err = followerConnection.Write(intToByte(dbWriteSize))
  512. if err != nil {
  513. panic(err)
  514. }
  515. }
  516. func addTestTweets() {
  517. //creates test tweets
  518. tweets := make([]lib.Tweet, 5)
  519. for i := range tweets {
  520. j := i
  521. if i == 1 {
  522. j = 0
  523. }
  524. text := "Text " + strconv.Itoa(i)
  525. var topics []string
  526. topics = append(topics, "Topic "+strconv.Itoa(j))
  527. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  528. }
  529. lib.NewEntries(tweets, 0)
  530. }
  531. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  532. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, startTime time.Time) {
  533. gotClient := make([]byte, 1)
  534. gotClient[0] = 0
  535. //wait until time is up
  536. for len(phase3Channel) == 0 {
  537. if time.Since(startTime) > maxTimePerRound {
  538. //tells follower that this worker is done
  539. _, err := followerConnection.Write(gotClient)
  540. if err != nil {
  541. panic(err)
  542. }
  543. wg.Done()
  544. return
  545. }
  546. time.Sleep(1 * time.Second)
  547. }
  548. for clientConnection := range phase3Channel {
  549. gotClient[0] = 1
  550. //tells follower that this worker got a clientConnection
  551. _, err := followerConnection.Write(gotClient)
  552. if err != nil {
  553. panic(err)
  554. }
  555. _, err = clientConnection.Write(phase)
  556. if err != nil {
  557. panic(err)
  558. }
  559. /*
  560. possible Values
  561. 0 : new client
  562. leader expects sharedSecrets, expects pirQuery
  563. 1 : update needed
  564. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  565. 2 : no update needed
  566. nothing
  567. */
  568. subPhase := make([]byte, 1)
  569. //gets the data for the current client
  570. var clientKeys = clientData[clientConnection.RemoteAddr()]
  571. var roundsParticipating = clientKeys.roundsParticipating
  572. //client participates for the first time
  573. if roundsParticipating == 0 {
  574. subPhase[0] = 0
  575. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  576. subPhase[0] = 1
  577. } else {
  578. subPhase[0] = 2
  579. }
  580. //tells client what leader expects
  581. _, err = clientConnection.Write(subPhase)
  582. if err != nil {
  583. panic(err)
  584. }
  585. //tells follower what will happen
  586. _, err = followerConnection.Write(subPhase)
  587. if err != nil {
  588. panic(err)
  589. }
  590. //sends clients publicKey so follower knows which client is being served
  591. _, err = followerConnection.Write(clientKeys.PublicKey[:])
  592. if err != nil {
  593. panic(err)
  594. }
  595. //increases rounds participating for client
  596. clientKeys.roundsParticipating = roundsParticipating + 1
  597. //declaring variables here to prevent dupclicates later
  598. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  599. if subPhase[0] == 0 {
  600. sendTopicLists(clientConnection)
  601. clientKeys, _ = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]))
  602. } else if subPhase[0] == 1 {
  603. sendTopicLists(clientConnection)
  604. //updates sharedSecret
  605. sharedSecret = sha256.Sum256(sharedSecret[:])
  606. clientKeys.SharedSecret = sharedSecret
  607. clientKeys, _ = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]))
  608. }
  609. getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  610. wantsArchive := make([]byte, 1)
  611. _, err = clientConnection.Read(wantsArchive)
  612. if err != nil {
  613. panic(err)
  614. }
  615. followerConnection.Write(wantsArchive)
  616. if err != nil {
  617. panic(err)
  618. }
  619. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  620. _, archiveQuerys := handlePirQuery(clientKeys, clientConnection, followerConnection, -1)
  621. getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  622. }
  623. //saves all changes for client
  624. clientData[clientConnection.RemoteAddr()] = clientKeys
  625. phase1Channel <- clientConnection
  626. for {
  627. if time.Since(startTime) < maxTimePerRound {
  628. //this worker handles the next client
  629. if len(phase3Channel) > 0 {
  630. break
  631. //this worker waits for next client
  632. } else {
  633. time.Sleep(1 * time.Second)
  634. }
  635. //times up
  636. } else {
  637. //tells follower that this worker is done
  638. gotClient[0] = 0
  639. _, err := followerConnection.Write(gotClient)
  640. if err != nil {
  641. panic(err)
  642. }
  643. wg.Done()
  644. return
  645. }
  646. }
  647. }
  648. }
  649. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) {
  650. tmpNeededSubscriptions := neededSubscriptions
  651. if archiveQuerys != nil {
  652. tmpNeededSubscriptions = len(archiveQuerys)
  653. }
  654. for i := 0; i < tmpNeededSubscriptions; i++ {
  655. //gets all requested tweets
  656. var tweets []byte
  657. if archiveQuerys == nil {
  658. tweets = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0)
  659. } else {
  660. tweets = lib.GetTweets(archiveQuerys[i], dataLength, 1)
  661. }
  662. //expand sharedSecret so it is of right length
  663. expandBy := len(tweets) / 32
  664. var expandedSharedSecret []byte
  665. for i := 0; i < expandBy; i++ {
  666. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  667. }
  668. //Xor's sharedSecret with all tweets
  669. lib.Xor(expandedSharedSecret[:], tweets)
  670. //receives tweets from follower and Xor's them in
  671. tweetsLengthBytes := make([]byte, 4)
  672. _, err := followerConnection.Read(tweetsLengthBytes)
  673. if err != nil {
  674. panic(err)
  675. }
  676. tweetsReceivedLength := byteToInt(tweetsLengthBytes)
  677. receivedTweets := make([]byte, tweetsReceivedLength)
  678. _, err = followerConnection.Read(receivedTweets)
  679. if err != nil {
  680. panic(err)
  681. }
  682. lib.Xor(receivedTweets, tweets)
  683. //sends tweets to client
  684. tweetsLengthBytes = intToByte(len(tweets))
  685. _, err = clientConnection.Write(tweetsLengthBytes)
  686. if err != nil {
  687. panic(err)
  688. }
  689. _, err = clientConnection.Write(tweets)
  690. if err != nil {
  691. panic(err)
  692. }
  693. }
  694. }
  695. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int) (clientKeys, [][]byte) {
  696. clientPublicKey := clientKeys.PublicKey
  697. //gets the msg length
  698. msgLengthBytes := make([]byte, 4)
  699. _, err := clientConnection.Read(msgLengthBytes)
  700. if err != nil {
  701. panic(err)
  702. }
  703. msgLength := byteToInt(msgLengthBytes)
  704. leaderBox := make([]byte, msgLength)
  705. followerBox := make([]byte, msgLength)
  706. //gets the leader box
  707. _, err = clientConnection.Read(leaderBox)
  708. if err != nil {
  709. panic(err)
  710. }
  711. //gets the follower box
  712. _, err = clientConnection.Read(followerBox)
  713. if err != nil {
  714. panic(err)
  715. }
  716. tmpNeededSubscriptions := neededSubscriptions
  717. tmpTopicAmount := topicAmount
  718. if subPhase == -1 {
  719. archiveNeededSubscriptions := make([]byte, 4)
  720. _, err = clientConnection.Read(archiveNeededSubscriptions)
  721. if err != nil {
  722. panic(err)
  723. }
  724. _, err = followerConnection.Write(archiveNeededSubscriptions)
  725. if err != nil {
  726. panic(err)
  727. }
  728. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  729. tmpTopicAmount = archiveTopicAmount
  730. }
  731. //send length to follower
  732. _, err = followerConnection.Write(msgLengthBytes)
  733. if err != nil {
  734. panic(err)
  735. }
  736. //send box to follower
  737. _, err = followerConnection.Write(followerBox)
  738. if err != nil {
  739. panic(err)
  740. }
  741. var decryptNonce [24]byte
  742. copy(decryptNonce[:], leaderBox[:24])
  743. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  744. if !ok {
  745. panic("pirQuery decryption not ok")
  746. }
  747. //if sharedSecret is send
  748. if subPhase == 0 {
  749. //bs!
  750. var tmpSharedSecret [32]byte
  751. for index := 0; index < 32; index++ {
  752. tmpSharedSecret[index] = decrypted[index]
  753. }
  754. clientKeys.SharedSecret = tmpSharedSecret
  755. decrypted = decrypted[32:]
  756. }
  757. //transforms byteArray to ints of wanted topics
  758. pirQueryFlattened := decrypted
  759. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  760. for i := range pirQuerys {
  761. pirQuerys[i] = make([]byte, tmpTopicAmount)
  762. }
  763. for i := 0; i < tmpNeededSubscriptions; i++ {
  764. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  765. }
  766. //sets the pirQuery for the client in case whe are not archiving
  767. if subPhase != -1 {
  768. clientKeys.PirQuery = pirQuerys
  769. }
  770. return clientKeys, pirQuerys
  771. }
  772. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  773. var topics []string
  774. var topic string
  775. var position int = 0
  776. for _, letter := range topicsAsBytes {
  777. if string(letter) == "," {
  778. topics[position] = topic
  779. topic = ""
  780. position++
  781. } else {
  782. topic = topic + string(letter)
  783. }
  784. }
  785. return topics
  786. }
  787. func byteToInt(myBytes []byte) (x int) {
  788. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  789. return
  790. }
  791. func sendTopicLists(clientConnection net.Conn) {
  792. for i := 0; i < 2; i++ {
  793. var topicList []byte
  794. if i == 0 {
  795. topicList, topicAmount = lib.GetTopicList(i)
  796. } else {
  797. topicList, archiveTopicAmount = lib.GetTopicList(i)
  798. }
  799. topicListLengthBytes := intToByte(len(topicList))
  800. _, err := clientConnection.Write(topicListLengthBytes)
  801. if err != nil {
  802. panic(err)
  803. }
  804. _, err = clientConnection.Write(topicList)
  805. if err != nil {
  806. panic(err)
  807. }
  808. }
  809. }
  810. func intToByte(myInt int) (retBytes []byte) {
  811. retBytes = make([]byte, 4)
  812. retBytes[3] = byte((myInt >> 24) & 0xff)
  813. retBytes[2] = byte((myInt >> 16) & 0xff)
  814. retBytes[1] = byte((myInt >> 8) & 0xff)
  815. retBytes[0] = byte(myInt & 0xff)
  816. return
  817. }