leader.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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 = 128
  52. var dbWriteSize int = 100
  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("error", 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("error", err)
  152. clientConnection.Close()
  153. break
  154. }
  155. //send follower publicKey
  156. _, err = clientConnection.Write(followerPublicKey[:])
  157. if err != nil {
  158. fmt.Println("error", 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("error", 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 Round", round)
  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. fmt.Println("pirQuery decryption not ok")
  884. return clientKeys, nil, true
  885. }
  886. //if sharedSecret is send
  887. if subPhase == 0 {
  888. var tmpSharedSecret [32]byte
  889. for index := 0; index < 32; index++ {
  890. tmpSharedSecret[index] = decrypted[index]
  891. }
  892. clientKeys.SharedSecret = tmpSharedSecret
  893. decrypted = decrypted[32:]
  894. }
  895. if doAuditing {
  896. result := make([][]byte, 1)
  897. result[0] = decrypted
  898. return clientKeys, result, false
  899. }
  900. //transforms byteArray to ints of wanted topics
  901. pirQueryFlattened := decrypted
  902. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  903. for i := range pirQuerys {
  904. pirQuerys[i] = make([]byte, tmpTopicAmount)
  905. }
  906. for i := 0; i < tmpNeededSubscriptions; i++ {
  907. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  908. }
  909. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  910. if subPhase != -1 {
  911. clientKeys.PirQuery = pirQuerys
  912. }
  913. return clientKeys, pirQuerys, false
  914. }
  915. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  916. var topics []string
  917. var topic string
  918. var position int = 0
  919. for _, letter := range topicsAsBytes {
  920. if string(letter) == "," {
  921. topics[position] = topic
  922. topic = ""
  923. position++
  924. } else {
  925. topic = topic + string(letter)
  926. }
  927. }
  928. return topics
  929. }
  930. func byteToInt(myBytes []byte) (x int) {
  931. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  932. return
  933. }
  934. //returns true if error occured
  935. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  936. for i := 0; i < 2; i++ {
  937. var topicList []byte
  938. if i == 0 {
  939. topicList, topicAmount = lib.GetTopicList(i)
  940. } else {
  941. topicList, archiveTopicAmount = lib.GetTopicList(i)
  942. }
  943. topicListLengthBytes := intToByte(len(topicList))
  944. if !setup {
  945. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  946. if err {
  947. return true
  948. }
  949. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  950. if err {
  951. return true
  952. }
  953. } else {
  954. _, err := clientConnection.Write(topicListLengthBytes)
  955. if err != nil {
  956. return true
  957. }
  958. _, err = clientConnection.Write(topicList)
  959. if err != nil {
  960. return true
  961. }
  962. }
  963. }
  964. return false
  965. }
  966. //sends the array to the connection
  967. func writeTo(connection net.Conn, array []byte) {
  968. _, err := connection.Write(array)
  969. if err != nil {
  970. panic(err)
  971. }
  972. }
  973. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  974. var err error
  975. if connection.RemoteAddr().String() == follower {
  976. arrayWError := make([]byte, 1)
  977. arrayWError = append(arrayWError, array[:]...)
  978. _, err = connection.Write(arrayWError)
  979. } else {
  980. _, err = connection.Write(array)
  981. }
  982. if err != nil {
  983. //lets follower know that client has disconnected unexpectedly
  984. if connection.RemoteAddr().String() != follower {
  985. fmt.Println("error", err)
  986. array := make([]byte, size)
  987. array[0] = 1
  988. _, err = followerConnection.Write(array)
  989. if err != nil {
  990. panic(err)
  991. }
  992. return true
  993. } else {
  994. panic(err)
  995. }
  996. }
  997. return false
  998. }
  999. //reads an array which is returned and of size "size" from the connection
  1000. //returns true if error occured
  1001. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1002. array := make([]byte, size)
  1003. _, err := connection.Read(array)
  1004. if err != nil {
  1005. //lets follower know that client has disconnected unexpectedly
  1006. if connection.RemoteAddr().String() != follower {
  1007. fmt.Println("error", err)
  1008. array := make([]byte, sizeError)
  1009. array[0] = 1
  1010. _, err = followerConnection.Write(array)
  1011. if err != nil {
  1012. panic(err)
  1013. }
  1014. return nil, true
  1015. } else {
  1016. panic(err)
  1017. }
  1018. }
  1019. return array, false
  1020. }
  1021. func intToByte(myInt int) (retBytes []byte) {
  1022. retBytes = make([]byte, 4)
  1023. retBytes[3] = byte((myInt >> 24) & 0xff)
  1024. retBytes[2] = byte((myInt >> 16) & 0xff)
  1025. retBytes[1] = byte((myInt >> 8) & 0xff)
  1026. retBytes[0] = byte(myInt & 0xff)
  1027. return
  1028. }