leader.go 30 KB

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