leader.go 26 KB

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