leader.go 30 KB

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