leader.go 31 KB

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