leader.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. C.initializeServer(C.int(numThreads))
  76. //calls follower for setup
  77. conf := &tls.Config{
  78. InsecureSkipVerify: true,
  79. }
  80. followerConnection, err := tls.Dial("tcp", follower, conf)
  81. if err != nil {
  82. panic(err)
  83. }
  84. followerConnection.SetDeadline(time.Time{})
  85. //receives follower publicKey
  86. var tmpFollowerPubKey [32]byte
  87. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  88. if err != nil {
  89. panic(err)
  90. }
  91. followerPublicKey = &tmpFollowerPubKey
  92. //send publicKey to follower
  93. writeTo(followerConnection, leaderPublicKey[:])
  94. //goroutine for accepting new clients
  95. go func() {
  96. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  97. if err != nil {
  98. panic(err)
  99. }
  100. // Generate a pem block with the private key
  101. keyPem := pem.EncodeToMemory(&pem.Block{
  102. Type: "RSA PRIVATE KEY",
  103. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  104. })
  105. tml := x509.Certificate{
  106. // you can add any attr that you need
  107. NotBefore: time.Now(),
  108. NotAfter: time.Now().AddDate(5, 0, 0),
  109. // you have to generate a different serial number each execution
  110. SerialNumber: big.NewInt(123123),
  111. Subject: pkix.Name{
  112. CommonName: "New Name",
  113. Organization: []string{"New Org."},
  114. },
  115. BasicConstraintsValid: true,
  116. }
  117. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  118. if err != nil {
  119. panic(err)
  120. }
  121. // Generate a pem block with the certificate
  122. certPem := pem.EncodeToMemory(&pem.Block{
  123. Type: "CERTIFICATE",
  124. Bytes: cert,
  125. })
  126. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  127. if err != nil {
  128. panic(err)
  129. }
  130. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  131. //listens for clients
  132. lnClients, err := tls.Listen("tcp", ":4441", config)
  133. if err != nil {
  134. panic(err)
  135. }
  136. defer lnClients.Close()
  137. for {
  138. clientConnection, err := lnClients.Accept()
  139. if err != nil {
  140. fmt.Println(err)
  141. }
  142. clientConnection.SetDeadline(time.Time{})
  143. //sends topicList so client can participate in phase 3 asap
  144. errorBool := sendTopicLists(clientConnection, followerConnection, true)
  145. if errorBool {
  146. break
  147. }
  148. //send leader publicKey
  149. _, err = clientConnection.Write(leaderPublicKey[:])
  150. if err != nil {
  151. fmt.Println(err)
  152. clientConnection.Close()
  153. break
  154. }
  155. //send follower publicKey
  156. _, err = clientConnection.Write(followerPublicKey[:])
  157. if err != nil {
  158. fmt.Println(err)
  159. clientConnection.Close()
  160. break
  161. }
  162. var clientPublicKey *[32]byte
  163. var tmpClientPublicKey [32]byte
  164. //gets publicKey from client
  165. _, err = clientConnection.Read(tmpClientPublicKey[:])
  166. if err != nil {
  167. fmt.Println(err)
  168. clientConnection.Close()
  169. break
  170. }
  171. clientPublicKey = &tmpClientPublicKey
  172. //this is the key for map(client data)
  173. remoteAddress := clientConnection.RemoteAddr()
  174. //pirQuery will be added in phase 3
  175. //bs! only want to set roundsParticipating and answerAmount to 0, mb there is a better way
  176. //will work for now
  177. var emptyArray [32]byte
  178. var emptyByteArray [][]byte
  179. keys := clientKeys{0, clientPublicKey, emptyArray, emptyByteArray}
  180. m.Lock()
  181. clientData[remoteAddress] = keys
  182. m.Unlock()
  183. phase1Channel <- clientConnection
  184. }
  185. }()
  186. wg := &sync.WaitGroup{}
  187. //the current phase
  188. phase := make([]byte, 1)
  189. for {
  190. startTime = time.Now()
  191. phase[0] = 1
  192. fmt.Println("Phase 1")
  193. //creates a new write Db for this round
  194. for i := 0; i < dbWriteSize; i++ {
  195. C.createDb(C.int(1), C.int(dataLength))
  196. }
  197. //creates a new db containing virtual addresses for auditing
  198. virtualAddresses := createVirtualAddresses()
  199. //send all virtualAddresses to follower
  200. for i := 0; i <= dbWriteSize; i++ {
  201. writeTo(followerConnection, intToByte(virtualAddresses[i]))
  202. }
  203. for id := 0; id < numThreads; id++ {
  204. wg.Add(1)
  205. followerConnection, err := tls.Dial("tcp", follower, conf)
  206. if err != nil {
  207. panic(err)
  208. }
  209. followerConnection.SetDeadline(time.Time{})
  210. go phase1(id, phase, followerConnection, wg, m, startTime, virtualAddresses)
  211. }
  212. wg.Wait()
  213. fmt.Println("Phase 2")
  214. followerConnection, err := tls.Dial("tcp", follower, conf)
  215. if err != nil {
  216. panic(err)
  217. }
  218. followerConnection.SetDeadline(time.Time{})
  219. phase2(followerConnection)
  220. fmt.Println("Phase 3")
  221. //no tweets -> continue to phase 1 and mb get tweets
  222. topicList, topicAmount = lib.GetTopicList(0)
  223. if len(topicList) == 0 {
  224. continue
  225. }
  226. phase[0] = 3
  227. startTime = time.Now()
  228. for id := 0; id < numThreads; id++ {
  229. wg.Add(1)
  230. followerConnection, err := tls.Dial("tcp", follower, conf)
  231. if err != nil {
  232. panic(err)
  233. }
  234. followerConnection.SetDeadline(time.Time{})
  235. go phase3(id, phase, followerConnection, wg, startTime, m)
  236. }
  237. wg.Wait()
  238. lib.CleanUpdbR(round)
  239. round++
  240. }
  241. }
  242. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, startTime time.Time, virtualAddresses []int) {
  243. roundAsBytes := intToByte(round)
  244. gotClient := make([]byte, 1)
  245. gotClient[0] = 0
  246. //wait until time is up
  247. for len(phase1Channel) == 0 {
  248. if time.Since(startTime) > maxTimePerRound {
  249. //tells follower that this worker is done
  250. writeTo(followerConnection, gotClient)
  251. wg.Done()
  252. return
  253. }
  254. time.Sleep(1 * time.Second)
  255. }
  256. for clientConnection := range phase1Channel {
  257. gotClient[0] = 1
  258. //tells follower that this worker got a clientConnection
  259. writeTo(followerConnection, gotClient)
  260. //sends clients publicKey to follower
  261. m.RLock()
  262. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  263. m.RUnlock()
  264. writeTo(followerConnection, clientPublicKey[:])
  265. //setup the worker-specific db
  266. dbSize := int(C.dbSize)
  267. db := make([][]byte, dbSize)
  268. for i := 0; i < dbSize; i++ {
  269. db[i] = make([]byte, int(C.db[i].dataSize))
  270. }
  271. //tells client that phase 1 has begun
  272. errorBool := writeToWError(clientConnection, phase, followerConnection, 5)
  273. if errorBool {
  274. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  275. if contBool {
  276. continue
  277. } else {
  278. return
  279. }
  280. }
  281. //tells client current dbWriteSize
  282. errorBool = writeToWError(clientConnection, intToByte(dbWriteSize), followerConnection, 5)
  283. if errorBool {
  284. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  285. if contBool {
  286. continue
  287. } else {
  288. return
  289. }
  290. }
  291. //tells client current round
  292. errorBool = writeToWError(clientConnection, roundAsBytes, followerConnection, 5)
  293. if errorBool {
  294. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  295. if contBool {
  296. continue
  297. } else {
  298. return
  299. }
  300. }
  301. m.RLock()
  302. var clientKeys = clientData[clientConnection.RemoteAddr()]
  303. m.RUnlock()
  304. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  305. if errorBool {
  306. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  307. if contBool {
  308. continue
  309. } else {
  310. return
  311. }
  312. }
  313. errorBool = getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  314. if errorBool {
  315. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  316. if contBool {
  317. continue
  318. } else {
  319. return
  320. }
  321. }
  322. m.Lock()
  323. clientData[clientConnection.RemoteAddr()] = clientKeys
  324. m.Unlock()
  325. //accept dpfQuery from client
  326. dpfLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  327. if errorBool {
  328. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  329. if contBool {
  330. continue
  331. } else {
  332. return
  333. }
  334. }
  335. dpfLength := byteToInt(dpfLengthBytes)
  336. dpfQueryAEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  337. if errorBool {
  338. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  339. if contBool {
  340. continue
  341. } else {
  342. return
  343. }
  344. }
  345. dpfQueryBEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  346. if errorBool {
  347. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  348. if contBool {
  349. continue
  350. } else {
  351. return
  352. }
  353. }
  354. writeToWError(followerConnection, dpfLengthBytes, nil, 0)
  355. writeToWError(followerConnection, dpfQueryBEncrypted, nil, 0)
  356. //decrypt dpfQueryA for sorting into db
  357. var decryptNonce [24]byte
  358. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  359. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  360. if !ok {
  361. panic("dpfQueryA decryption not ok")
  362. }
  363. ds := int(C.db[0].dataSize)
  364. dataShareLeader := make([]byte, ds)
  365. pos := C.getUint128_t(C.int(virtualAddresses[dbWriteSize]))
  366. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  367. dataShareFollower, _ := readFrom(followerConnection, ds, nil, 0)
  368. writeToWError(followerConnection, dataShareLeader, nil, 0)
  369. auditXOR := make([]byte, ds)
  370. passedAudit := true
  371. for i := 0; i < ds; i++ {
  372. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  373. //client tried to write to a position that is not a virtuallAddress
  374. if auditXOR[i] != 0 {
  375. clientConnection.Close()
  376. passedAudit = false
  377. }
  378. }
  379. if passedAudit {
  380. //run dpf, xor into local db
  381. for i := 0; i < dbSize; i++ {
  382. ds := int(C.db[i].dataSize)
  383. dataShare := make([]byte, ds)
  384. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  385. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  386. for j := 0; j < ds; j++ {
  387. db[i][j] = db[i][j] ^ dataShare[j]
  388. }
  389. }
  390. //xor the worker's DB into the main DB
  391. for i := 0; i < dbSize; i++ {
  392. m.Lock()
  393. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  394. m.Unlock()
  395. }
  396. phase3Channel <- clientConnection
  397. }
  398. //loop that waits for new client or leaves phase1 if time is up
  399. for {
  400. if time.Since(startTime) < maxTimePerRound {
  401. //this worker handles the next client
  402. if len(phase1Channel) > 0 {
  403. break
  404. //this worker waits for next client
  405. } else {
  406. time.Sleep(1 * time.Second)
  407. }
  408. //times up
  409. } else {
  410. //tells follower that this worker is done
  411. gotClient[0] = 0
  412. writeTo(followerConnection, gotClient)
  413. wg.Done()
  414. return
  415. }
  416. }
  417. }
  418. }
  419. func phase2(followerConnection net.Conn) {
  420. //gets current seed
  421. seedLeader := make([]byte, 16)
  422. C.readSeed((*C.uchar)(&seedLeader[0]))
  423. //get data
  424. dbSize := int(C.dbSize)
  425. tmpdbLeader := make([][]byte, dbSize)
  426. for i := range tmpdbLeader {
  427. tmpdbLeader[i] = make([]byte, dataLength)
  428. }
  429. for i := 0; i < dbSize; i++ {
  430. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  431. }
  432. //writes seed to follower
  433. writeTo(followerConnection, seedLeader)
  434. //write data to follower
  435. //this is surely inefficent
  436. for i := 0; i < dbSize; i++ {
  437. writeTo(followerConnection, tmpdbLeader[i])
  438. }
  439. //receive seed from follower
  440. seedFollower, _ := readFrom(followerConnection, 16, nil, 0)
  441. //receive data from follower
  442. tmpdbFollower := make([][]byte, dbSize)
  443. for i := range tmpdbFollower {
  444. tmpdbFollower[i] = make([]byte, dataLength)
  445. }
  446. for i := 0; i < dbSize; i++ {
  447. tmpdbFollower[i], _ = readFrom(followerConnection, dataLength, nil, 0)
  448. }
  449. //put together the db
  450. tmpdb := make([][]byte, dbSize)
  451. for i := range tmpdb {
  452. tmpdb[i] = make([]byte, dataLength)
  453. }
  454. //get own Ciphers
  455. ciphersLeader := make([]*C.uchar, dbSize)
  456. for i := 0; i < dbSize; i++ {
  457. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  458. }
  459. for i := 0; i < dbSize; i++ {
  460. C.getCipher(1, C.int(i), ciphersLeader[i])
  461. }
  462. //send own Ciphers to follower
  463. for i := 0; i < dbSize; i++ {
  464. writeTo(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  465. }
  466. //receive ciphers from follower
  467. ciphersFollower := make([]byte, dbSize*16)
  468. for i := 0; i < dbSize; i++ {
  469. _, err := followerConnection.Read(ciphersFollower[i*16:])
  470. if err != nil {
  471. panic(err)
  472. }
  473. }
  474. //put in ciphers from follower
  475. for i := 0; i < dbSize; i++ {
  476. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  477. }
  478. //decrypt each row
  479. for i := 0; i < dbSize; i++ {
  480. 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]))
  481. }
  482. var tweets []lib.Tweet
  483. var currentPublisherAmount int = 0
  484. for i := 0; i < dbSize; i++ {
  485. //discard cover message
  486. if tmpdb[i][0] == 0 {
  487. continue
  488. } else {
  489. currentPublisherAmount++
  490. //reconstruct tweet
  491. var position int = 0
  492. var topics []string
  493. var topic string
  494. var text string
  495. for _, letter := range tmpdb[i] {
  496. if string(letter) == ";" {
  497. if topic != "" {
  498. topics = append(topics, topic)
  499. topic = ""
  500. }
  501. position++
  502. } else {
  503. if position == 0 {
  504. if string(letter) == "," {
  505. topics = append(topics, topic)
  506. topic = ""
  507. } else {
  508. topic = topic + string(letter)
  509. }
  510. } else if position == 1 {
  511. text = text + string(letter)
  512. }
  513. }
  514. }
  515. tweet := lib.Tweet{"", -1, topics, text, round}
  516. tweets = append(tweets, tweet)
  517. }
  518. }
  519. //fmt.Println("tweets recovered: ", tweets)
  520. //sort into read db
  521. lib.NewEntries(tweets, 0)
  522. C.resetDb()
  523. //calculates the publisherAverage over the last publisherRounds rounds
  524. index := round % publisherRounds
  525. publisherHistory[index] = currentPublisherAmount
  526. var publisherAmount int
  527. for _, num := range publisherHistory {
  528. publisherAmount += num
  529. }
  530. publisherAverage := 0
  531. if round < publisherRounds {
  532. publisherAverage = publisherAmount / round
  533. } else {
  534. publisherAverage = publisherAmount / publisherRounds
  535. }
  536. //calculates the dbWriteSize for this round
  537. dbWriteSize = int(math.Ceil(19.5 * float64(publisherAverage)))
  538. if dbWriteSize < 100 {
  539. dbWriteSize = 100
  540. }
  541. //writes dbWriteSize of current round to follower
  542. writeTo(followerConnection, intToByte(dbWriteSize))
  543. }
  544. func addTestTweets() {
  545. //creates test tweets
  546. tweets := make([]lib.Tweet, 5)
  547. for i := range tweets {
  548. j := i
  549. if i == 1 {
  550. j = 0
  551. }
  552. text := "Text " + strconv.Itoa(i)
  553. var topics []string
  554. topics = append(topics, "Topic "+strconv.Itoa(j))
  555. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  556. }
  557. lib.NewEntries(tweets, 0)
  558. }
  559. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  560. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, startTime time.Time, m *sync.RWMutex) {
  561. gotClient := make([]byte, 1)
  562. gotClient[0] = 0
  563. //wait until time is up
  564. for len(phase3Channel) == 0 {
  565. if time.Since(startTime) > maxTimePerRound {
  566. //tells follower that this worker is done
  567. writeToWError(followerConnection, gotClient, nil, 0)
  568. wg.Done()
  569. return
  570. }
  571. time.Sleep(1 * time.Second)
  572. }
  573. for clientConnection := range phase3Channel {
  574. gotClient[0] = 1
  575. //tells follower that this worker got a clientConnection
  576. writeToWError(followerConnection, gotClient, nil, 0)
  577. //tells client current phase
  578. errorBool := writeToWError(clientConnection, phase, followerConnection, 2)
  579. if errorBool {
  580. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  581. if contBool {
  582. continue
  583. } else {
  584. return
  585. }
  586. }
  587. /*
  588. possible Values
  589. 0 : new client
  590. leader expects sharedSecrets, expects pirQuery
  591. 1 : update needed
  592. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  593. 2 : no update needed
  594. nothing
  595. */
  596. subPhase := make([]byte, 1)
  597. //gets the data for the current client
  598. m.RLock()
  599. var clientKeys = clientData[clientConnection.RemoteAddr()]
  600. m.RUnlock()
  601. var roundsParticipating = clientKeys.roundsParticipating
  602. //client participates for the first time
  603. if roundsParticipating == 0 {
  604. subPhase[0] = 0
  605. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  606. subPhase[0] = 1
  607. } else {
  608. subPhase[0] = 2
  609. }
  610. //tells client what leader expects
  611. errorBool = writeToWError(clientConnection, subPhase, followerConnection, 2)
  612. if errorBool {
  613. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  614. if contBool {
  615. continue
  616. } else {
  617. return
  618. }
  619. }
  620. //tells follower what will happen
  621. writeToWError(followerConnection, subPhase, nil, 0)
  622. //sends clients publicKey so follower knows which client is being served
  623. writeTo(followerConnection, clientKeys.PublicKey[:])
  624. //increases rounds participating for client
  625. clientKeys.roundsParticipating = roundsParticipating + 1
  626. //declaring variables here to prevent dupclicates later
  627. m.RLock()
  628. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  629. m.RUnlock()
  630. if subPhase[0] == 0 {
  631. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  632. if errorBool {
  633. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  634. if contBool {
  635. continue
  636. } else {
  637. return
  638. }
  639. }
  640. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  641. if errorBool {
  642. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  643. if contBool {
  644. continue
  645. } else {
  646. return
  647. }
  648. }
  649. } else if subPhase[0] == 1 {
  650. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  651. if errorBool {
  652. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  653. if contBool {
  654. continue
  655. } else {
  656. return
  657. }
  658. }
  659. //updates sharedSecret
  660. sharedSecret = sha256.Sum256(sharedSecret[:])
  661. clientKeys.SharedSecret = sharedSecret
  662. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  663. if errorBool {
  664. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  665. if contBool {
  666. continue
  667. } else {
  668. return
  669. }
  670. }
  671. }
  672. errorBool = getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  673. if errorBool {
  674. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  675. if contBool {
  676. continue
  677. } else {
  678. return
  679. }
  680. }
  681. wantsArchive, errorBool := readFrom(clientConnection, 1, followerConnection, 2)
  682. if errorBool {
  683. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  684. if contBool {
  685. continue
  686. } else {
  687. return
  688. }
  689. }
  690. writeToWError(followerConnection, wantsArchive, nil, 0)
  691. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  692. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  693. if errorBool {
  694. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  695. if contBool {
  696. continue
  697. } else {
  698. return
  699. }
  700. }
  701. errorBool = getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  702. if errorBool {
  703. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  704. if contBool {
  705. continue
  706. } else {
  707. return
  708. }
  709. }
  710. }
  711. //saves all changes for client
  712. m.Lock()
  713. clientData[clientConnection.RemoteAddr()] = clientKeys
  714. m.Unlock()
  715. phase1Channel <- clientConnection
  716. for {
  717. if time.Since(startTime) < maxTimePerRound {
  718. //this worker handles the next client
  719. if len(phase3Channel) > 0 {
  720. break
  721. //this worker waits for next client
  722. } else {
  723. time.Sleep(1 * time.Second)
  724. }
  725. //times up
  726. } else {
  727. //tells follower that this worker is done
  728. gotClient[0] = 0
  729. writeToWError(followerConnection, gotClient, nil, 0)
  730. wg.Done()
  731. return
  732. }
  733. }
  734. }
  735. }
  736. //returns true if there is another client
  737. func handleClientDC(wg *sync.WaitGroup, followerConnection net.Conn, channel chan net.Conn) bool {
  738. //loop that waits for new client or leaves phase1 if time is up
  739. for {
  740. if time.Since(startTime) < maxTimePerRound {
  741. //this worker handles the next client
  742. if len(channel) > 0 {
  743. return true
  744. //this worker waits for next client
  745. } else {
  746. time.Sleep(1 * time.Second)
  747. }
  748. //times up
  749. } else {
  750. //tells follower that this worker is done
  751. gotClient := make([]byte, 1)
  752. gotClient[0] = 0
  753. writeTo(followerConnection, gotClient)
  754. wg.Done()
  755. return false
  756. }
  757. }
  758. }
  759. func createVirtualAddresses() []int {
  760. //array will be filled with unique random ascending values
  761. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  762. //+1 to have a position to evaluate each received message
  763. arraySize := dbWriteSize + 1
  764. var maxInt int = int(math.Pow(2, 31))
  765. virtualAddresses := make([]int, arraySize)
  766. for i := 0; i < arraySize; i++ {
  767. virtualAddresses[i] = mr.Intn(maxInt)
  768. for j := 0; j < i; j++ {
  769. if virtualAddresses[i] == virtualAddresses[j] {
  770. i--
  771. break
  772. }
  773. }
  774. }
  775. sort.Ints(virtualAddresses)
  776. return virtualAddresses
  777. }
  778. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) bool {
  779. //xores all requested addresses into virtuallAddress
  780. virtualAddress := make([]byte, 4)
  781. for index, num := range pirQuery {
  782. if num == 1 {
  783. currentAddress := intToByte(virtualAddresses[index])
  784. for i := 0; i < 4; i++ {
  785. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  786. }
  787. }
  788. }
  789. //xores the sharedSecret
  790. for i := 0; i < 4; i++ {
  791. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  792. }
  793. virtualAddressFollower, _ := readFrom(followerConnection, 4, nil, 0)
  794. //xores the data from follower
  795. for i := 0; i < 4; i++ {
  796. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  797. }
  798. errorBool := writeToWError(clientConnection, virtualAddress, followerConnection, 5)
  799. return errorBool
  800. }
  801. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) bool {
  802. tmpNeededSubscriptions := neededSubscriptions
  803. if archiveQuerys != nil {
  804. tmpNeededSubscriptions = len(archiveQuerys)
  805. }
  806. tweets := make([][]byte, tmpNeededSubscriptions)
  807. for i := 0; i < tmpNeededSubscriptions; i++ {
  808. //gets all requested tweets
  809. if archiveQuerys == nil {
  810. tweets[i] = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0)
  811. } else {
  812. tweets[i] = lib.GetTweets(archiveQuerys[i], dataLength, 1)
  813. }
  814. //expand sharedSecret so it is of right length
  815. expandBy := len(tweets[i]) / 32
  816. var expandedSharedSecret []byte
  817. for i := 0; i < expandBy; i++ {
  818. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  819. }
  820. //Xor's sharedSecret with all tweets
  821. lib.Xor(expandedSharedSecret[:], tweets[i])
  822. //receives tweets from follower and Xor's them in
  823. tweetsLengthBytes, _ := readFrom(followerConnection, 4, nil, 0)
  824. tweetsReceivedLength := byteToInt(tweetsLengthBytes)
  825. receivedTweets, _ := readFrom(followerConnection, tweetsReceivedLength, nil, 0)
  826. lib.Xor(receivedTweets, tweets[i])
  827. }
  828. //sends tweets to client
  829. for i := 0; i < tmpNeededSubscriptions; i++ {
  830. tweetsLengthBytes := intToByte(len(tweets[i]))
  831. errorBool := writeToWError(clientConnection, tweetsLengthBytes, followerConnection, 2)
  832. if errorBool {
  833. return true
  834. }
  835. errorBool = writeToWError(clientConnection, tweets[i], followerConnection, 2)
  836. if errorBool {
  837. return true
  838. }
  839. }
  840. return false
  841. }
  842. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte, bool) {
  843. clientPublicKey := clientKeys.PublicKey
  844. //gets the msg length
  845. msgLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  846. if errorBool {
  847. return clientKeys, nil, true
  848. }
  849. msgLength := byteToInt(msgLengthBytes)
  850. //gets the leader box
  851. leaderBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  852. if errorBool {
  853. return clientKeys, nil, true
  854. }
  855. //gets the follower box
  856. followerBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  857. if errorBool {
  858. return clientKeys, nil, true
  859. }
  860. tmpNeededSubscriptions := neededSubscriptions
  861. tmpTopicAmount := topicAmount
  862. if subPhase == -1 {
  863. archiveNeededSubscriptions, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  864. if errorBool {
  865. return clientKeys, nil, true
  866. }
  867. writeToWError(followerConnection, archiveNeededSubscriptions, nil, 0)
  868. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  869. tmpTopicAmount = archiveTopicAmount
  870. }
  871. if doAuditing {
  872. tmpNeededSubscriptions = 1
  873. tmpTopicAmount = dbWriteSize
  874. }
  875. //send length to follower
  876. writeToWError(followerConnection, msgLengthBytes, nil, 0)
  877. //send box to follower
  878. writeToWError(followerConnection, followerBox, nil, 0)
  879. var decryptNonce [24]byte
  880. copy(decryptNonce[:], leaderBox[:24])
  881. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  882. if !ok {
  883. panic("pirQuery decryption not ok")
  884. }
  885. //if sharedSecret is send
  886. if subPhase == 0 {
  887. var tmpSharedSecret [32]byte
  888. for index := 0; index < 32; index++ {
  889. tmpSharedSecret[index] = decrypted[index]
  890. }
  891. clientKeys.SharedSecret = tmpSharedSecret
  892. decrypted = decrypted[32:]
  893. }
  894. if doAuditing {
  895. result := make([][]byte, 1)
  896. result[0] = decrypted
  897. return clientKeys, result, false
  898. }
  899. //transforms byteArray to ints of wanted topics
  900. pirQueryFlattened := decrypted
  901. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  902. for i := range pirQuerys {
  903. pirQuerys[i] = make([]byte, tmpTopicAmount)
  904. }
  905. for i := 0; i < tmpNeededSubscriptions; i++ {
  906. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  907. }
  908. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  909. if subPhase != -1 {
  910. clientKeys.PirQuery = pirQuerys
  911. }
  912. return clientKeys, pirQuerys, false
  913. }
  914. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  915. var topics []string
  916. var topic string
  917. var position int = 0
  918. for _, letter := range topicsAsBytes {
  919. if string(letter) == "," {
  920. topics[position] = topic
  921. topic = ""
  922. position++
  923. } else {
  924. topic = topic + string(letter)
  925. }
  926. }
  927. return topics
  928. }
  929. func byteToInt(myBytes []byte) (x int) {
  930. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  931. return
  932. }
  933. //returns true if error occured
  934. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  935. for i := 0; i < 2; i++ {
  936. var topicList []byte
  937. if i == 0 {
  938. topicList, topicAmount = lib.GetTopicList(i)
  939. } else {
  940. topicList, archiveTopicAmount = lib.GetTopicList(i)
  941. }
  942. topicListLengthBytes := intToByte(len(topicList))
  943. if !setup {
  944. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  945. if err {
  946. return true
  947. }
  948. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  949. if err {
  950. return true
  951. }
  952. } else {
  953. _, err := clientConnection.Write(topicListLengthBytes)
  954. if err != nil {
  955. return true
  956. }
  957. _, err = clientConnection.Write(topicList)
  958. if err != nil {
  959. return true
  960. }
  961. }
  962. }
  963. return false
  964. }
  965. //sends the array to the connection
  966. func writeTo(connection net.Conn, array []byte) {
  967. _, err := connection.Write(array)
  968. if err != nil {
  969. panic(err)
  970. }
  971. }
  972. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  973. var err error
  974. if connection.RemoteAddr().String() == follower {
  975. arrayWError := make([]byte, 1)
  976. arrayWError = append(arrayWError, array[:]...)
  977. _, err = connection.Write(arrayWError)
  978. } else {
  979. _, err = connection.Write(array)
  980. }
  981. if err != nil {
  982. //lets follower know that client has disconnected unexpectedly
  983. if connection.RemoteAddr().String() != follower {
  984. fmt.Println(err)
  985. array := make([]byte, size)
  986. array[0] = 1
  987. _, err = followerConnection.Write(array)
  988. if err != nil {
  989. panic(err)
  990. }
  991. return true
  992. } else {
  993. panic(err)
  994. }
  995. }
  996. return false
  997. }
  998. //reads an array which is returned and of size "size" from the connection
  999. //returns true if error occured
  1000. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1001. array := make([]byte, size)
  1002. _, err := connection.Read(array)
  1003. if err != nil {
  1004. //lets follower know that client has disconnected unexpectedly
  1005. if connection.RemoteAddr().String() != follower {
  1006. fmt.Println(err)
  1007. array := make([]byte, sizeError)
  1008. array[0] = 1
  1009. _, err = followerConnection.Write(array)
  1010. if err != nil {
  1011. panic(err)
  1012. }
  1013. return nil, true
  1014. } else {
  1015. panic(err)
  1016. }
  1017. }
  1018. return array, false
  1019. }
  1020. func intToByte(myInt int) (retBytes []byte) {
  1021. retBytes = make([]byte, 4)
  1022. retBytes[3] = byte((myInt >> 24) & 0xff)
  1023. retBytes[2] = byte((myInt >> 16) & 0xff)
  1024. retBytes[1] = byte((myInt >> 8) & 0xff)
  1025. retBytes[0] = byte(myInt & 0xff)
  1026. return
  1027. }