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